articles-backend-app

Форк
0
/
ArticleControllerTest.java 
468 строк · 17.9 Кб
1
package by.andd3dfx.controllers;
2

3
import static org.hamcrest.CoreMatchers.containsString;
4
import static org.hamcrest.CoreMatchers.is;
5
import static org.hamcrest.CoreMatchers.notNullValue;
6
import static org.hamcrest.MatcherAssert.assertThat;
7
import static org.hamcrest.Matchers.hasSize;
8
import static org.springframework.http.MediaType.APPLICATION_JSON;
9
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
10
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
11
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.patch;
12
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
13
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
14
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
15
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup;
16

17
import by.andd3dfx.ArticlesBackendAppApplication;
18
import by.andd3dfx.dto.ArticleDto;
19
import by.andd3dfx.dto.ArticleUpdateDto;
20
import by.andd3dfx.dto.AuthorDto;
21
import com.fasterxml.jackson.databind.ObjectMapper;
22
import java.io.IOException;
23
import java.time.LocalDateTime;
24
import org.junit.jupiter.api.BeforeEach;
25
import org.junit.jupiter.api.Test;
26
import org.springframework.beans.factory.annotation.Autowired;
27
import org.springframework.boot.test.context.SpringBootTest;
28
import org.springframework.test.context.web.WebAppConfiguration;
29
import org.springframework.test.web.servlet.MockMvc;
30
import org.springframework.web.context.WebApplicationContext;
31

32
@SpringBootTest(classes = ArticlesBackendAppApplication.class)
33
@WebAppConfiguration
34
class ArticleControllerTest {
35

36
    private MockMvc mockMvc;
37

38
    @Autowired
39
    private WebApplicationContext webApplicationContext;
40

41
    @Autowired
42
    private ObjectMapper objectMapper;
43

44
    @BeforeEach
45
    public void setup() {
46
        mockMvc = webAppContextSetup(webApplicationContext)
47
            .build();
48
    }
49

50
    @Test
51
    public void createArticle() throws Exception {
52
        ArticleDto articleDto = new ArticleDto();
53
        articleDto.setTitle("Some tittle value");
54
        articleDto.setSummary("Some summary value");
55
        articleDto.setText("Some text");
56
        AuthorDto authorDto = new AuthorDto();
57
        authorDto.setId(1L);
58
        articleDto.setAuthor(authorDto);
59

60
        mockMvc.perform(post("/api/v1/articles")
61
            .contentType(APPLICATION_JSON)
62
            .content(json(articleDto))
63
        )
64
            .andExpect(status().isCreated())
65
            .andExpect(jsonPath("$.id", notNullValue()))
66
            .andExpect(jsonPath("$.title", is(articleDto.getTitle())))
67
            .andExpect(jsonPath("$.summary", is(articleDto.getSummary())))
68
            .andExpect(jsonPath("$.text", is(articleDto.getText())))
69
            .andExpect(jsonPath("$.author.id", is(1)))
70
            .andExpect(jsonPath("$.dateCreated", notNullValue()))
71
            .andExpect(jsonPath("$.dateUpdated", notNullValue()));
72
    }
73

74
    @Test
75
    public void createArticleWithIdPopulated() throws Exception {
76
        ArticleDto articleDto = new ArticleDto();
77
        articleDto.setId(123L);
78
        articleDto.setTitle("Some tittle value");
79
        articleDto.setSummary("Some summary value");
80
        articleDto.setText("Some text");
81
        AuthorDto authorDto = new AuthorDto();
82
        authorDto.setId(1L);
83
        articleDto.setAuthor(authorDto);
84

85
        final String message = mockMvc.perform(post("/api/v1/articles")
86
            .contentType(APPLICATION_JSON)
87
            .content(json(articleDto))
88
        )
89
            .andExpect(status().isBadRequest())
90
            .andReturn().getResolvedException().getMessage();
91
        assertThat(message, containsString("Article id shouldn't be present"));
92
    }
93

94
    @Test
95
    public void createArticleWithoutTitle() throws Exception {
96
        ArticleDto articleDto = new ArticleDto();
97
        articleDto.setSummary("Some summary value");
98
        articleDto.setText("Some text");
99
        AuthorDto authorDto = new AuthorDto();
100
        authorDto.setId(1L);
101
        articleDto.setAuthor(authorDto);
102

103
        final String message = mockMvc.perform(post("/api/v1/articles")
104
            .contentType(APPLICATION_JSON)
105
            .content(json(articleDto))
106
        )
107
            .andExpect(status().isBadRequest())
108
            .andReturn().getResolvedException().getMessage();
109
        assertThat(message, containsString("Title should be populated"));
110
    }
111

112
    @Test
113
    public void createArticleWithEmptyTitle() throws Exception {
114
        ArticleDto articleDto = new ArticleDto();
115
        articleDto.setTitle("");
116
        articleDto.setSummary("Some summary value");
117
        articleDto.setText("Some text");
118
        AuthorDto authorDto = new AuthorDto();
119
        authorDto.setId(1L);
120
        articleDto.setAuthor(authorDto);
121

122
        final String message = mockMvc.perform(post("/api/v1/articles")
123
            .contentType(APPLICATION_JSON)
124
            .content(json(articleDto))
125
        )
126
            .andExpect(status().isBadRequest())
127
            .andReturn().getResolvedException().getMessage();
128
        assertThat(message, containsString("Title length must be between 1 and 100"));
129
    }
130

131
    @Test
132
    public void createArticleWithTooLongTitle() throws Exception {
133
        ArticleDto articleDto = new ArticleDto();
134
        articleDto.setTitle(createStringWithLength(101));
135
        articleDto.setSummary("Some summary value");
136
        articleDto.setText("Some text");
137
        AuthorDto authorDto = new AuthorDto();
138
        authorDto.setId(1L);
139
        articleDto.setAuthor(authorDto);
140

141
        String message = mockMvc.perform(post("/api/v1/articles")
142
            .contentType(APPLICATION_JSON)
143
            .content(json(articleDto))
144
        )
145
            .andExpect(status().isBadRequest())
146
            .andReturn().getResolvedException().getMessage();
147
        assertThat(message, containsString("Title length must be between 1 and 100"));
148
    }
149

150
    @Test
151
    public void createArticleWithTooLongSummary() throws Exception {
152
        ArticleDto articleDto = new ArticleDto();
153
        articleDto.setTitle("Some title");
154
        articleDto.setSummary(createStringWithLength(260));
155
        articleDto.setText("Some text");
156
        AuthorDto authorDto = new AuthorDto();
157
        authorDto.setId(1L);
158
        articleDto.setAuthor(authorDto);
159

160
        String message = mockMvc.perform(post("/api/v1/articles")
161
            .contentType(APPLICATION_JSON)
162
            .content(json(articleDto))
163
        )
164
            .andExpect(status().isBadRequest())
165
            .andReturn().getResolvedException().getMessage();
166
        assertThat(message, containsString("Summary length shouldn't be greater than 255"));
167
    }
168

169
    @Test
170
    public void createArticleWithoutText() throws Exception {
171
        ArticleDto articleDto = new ArticleDto();
172
        articleDto.setTitle("Some title");
173
        articleDto.setSummary("Some summary value");
174
        AuthorDto authorDto = new AuthorDto();
175
        authorDto.setId(1L);
176
        articleDto.setAuthor(authorDto);
177

178
        String message = mockMvc.perform(post("/api/v1/articles")
179
            .contentType(APPLICATION_JSON)
180
            .content(json(articleDto))
181
        )
182
            .andExpect(status().isBadRequest())
183
            .andReturn().getResolvedException().getMessage();
184
        assertThat(message, containsString("Text should be populated"));
185
    }
186

187
    @Test
188
    public void createArticleWithEmptyText() throws Exception {
189
        ArticleDto articleDto = new ArticleDto();
190
        articleDto.setTitle("Some title");
191
        articleDto.setSummary("Some summary value");
192
        articleDto.setText("");
193
        AuthorDto authorDto = new AuthorDto();
194
        authorDto.setId(1L);
195
        articleDto.setAuthor(authorDto);
196

197
        String message = mockMvc.perform(post("/api/v1/articles")
198
            .contentType(APPLICATION_JSON)
199
            .content(json(articleDto))
200
        )
201
            .andExpect(status().isBadRequest())
202
            .andReturn().getResolvedException().getMessage();
203
        assertThat(message, containsString("Text length should be 1 at least"));
204
    }
205

206
    @Test
207
    public void createArticleWithoutAuthor() throws Exception {
208
        ArticleDto articleDto = new ArticleDto();
209
        articleDto.setTitle("Some title");
210
        articleDto.setSummary("Some summary value");
211
        articleDto.setText("Some text");
212

213
        String message = mockMvc.perform(post("/api/v1/articles")
214
            .contentType(APPLICATION_JSON)
215
            .content(json(articleDto))
216
        )
217
            .andExpect(status().isBadRequest())
218
            .andReturn().getResolvedException().getMessage();
219
        assertThat(message, containsString("Author should be populated"));
220
    }
221

222
    @Test
223
    public void createArticleWithWrongAuthor() throws Exception {
224
        ArticleDto articleDto = new ArticleDto();
225
        articleDto.setTitle("Some title");
226
        articleDto.setSummary("Some summary value");
227
        articleDto.setText("Some text");
228
        AuthorDto authorDto = new AuthorDto();
229
        authorDto.setId(100L);
230
        articleDto.setAuthor(authorDto);
231

232
        String message = mockMvc.perform(post("/api/v1/articles")
233
            .contentType(APPLICATION_JSON)
234
            .content(json(articleDto))
235
        )
236
            .andExpect(status().isBadRequest())
237
            .andReturn().getResolvedException().getMessage();
238
        assertThat(message, containsString("Unknown author"));
239
    }
240

241
    @Test
242
    public void createArticleWithDateCreatedPopulated() throws Exception {
243
        ArticleDto articleDto = new ArticleDto();
244
        articleDto.setTitle("Some tittle value");
245
        articleDto.setSummary("Some summary value");
246
        articleDto.setText("Some text");
247
        AuthorDto authorDto = new AuthorDto();
248
        authorDto.setId(1L);
249
        articleDto.setAuthor(authorDto);
250
        articleDto.setDateCreated(LocalDateTime.now());
251

252
        String message = mockMvc.perform(post("/api/v1/articles")
253
            .contentType(APPLICATION_JSON)
254
            .content(json(articleDto))
255
        )
256
            .andExpect(status().isBadRequest())
257
            .andReturn().getResolvedException().getMessage();
258
        assertThat(message, containsString("DateCreated shouldn't be populated"));
259
    }
260

261
    @Test
262
    public void createArticleWithDateUpdatedPopulated() throws Exception {
263
        ArticleDto articleDto = new ArticleDto();
264
        articleDto.setTitle("Some tittle value");
265
        articleDto.setSummary("Some summary value");
266
        articleDto.setText("Some text");
267
        AuthorDto authorDto = new AuthorDto();
268
        authorDto.setId(1L);
269
        articleDto.setAuthor(authorDto);
270
        articleDto.setDateUpdated(LocalDateTime.now());
271

272
        String message = mockMvc.perform(post("/api/v1/articles")
273
            .contentType(APPLICATION_JSON)
274
            .content(json(articleDto))
275
        )
276
            .andExpect(status().isBadRequest())
277
            .andReturn().getResolvedException().getMessage();
278
        assertThat(message, containsString("DateUpdated shouldn't be populated"));
279
    }
280

281
    @Test
282
    public void deleteArticle() throws Exception {
283
        mockMvc.perform(delete("/api/v1/articles/1")
284
            .contentType(APPLICATION_JSON)
285
        )
286
            .andExpect(status().isNoContent());
287
    }
288

289
    @Test
290
    public void deleteAbsentArticle() throws Exception {
291
        mockMvc.perform(delete("/api/v1/articles/9999")
292
            .contentType(APPLICATION_JSON))
293
            .andExpect(status().isNotFound());
294
    }
295

296
    @Test
297
    public void readArticle() throws Exception {
298
        mockMvc.perform(get("/api/v1/articles/1")
299
            .contentType(APPLICATION_JSON)
300
        )
301
            .andExpect(status().isOk())
302
            .andExpect(jsonPath("$.id", is(1)));
303
    }
304

305
    @Test
306
    public void readAbsentArticle() throws Exception {
307
        mockMvc.perform(get("/api/v1/articles/345")
308
            .contentType(APPLICATION_JSON))
309
            .andExpect(status().isNotFound());
310
    }
311

312
    @Test
313
    public void readArticles() throws Exception {
314
        mockMvc.perform(get("/api/v1/articles")
315
            .contentType(APPLICATION_JSON)
316
        )
317
            .andExpect(status().isOk())
318
            .andExpect(jsonPath("$.content", hasSize(10)))
319
            .andExpect(jsonPath("$.number", is(0)))
320
            .andExpect(jsonPath("$.size", is(50)))
321
            .andExpect(jsonPath("$.totalPages", is(1)))
322
            .andExpect(jsonPath("$.totalElements", is(10)));
323
    }
324

325
    @Test
326
    public void readArticlesWithPageSizeLimit() throws Exception {
327
        mockMvc.perform(get("/api/v1/articles")
328
            .param("size", "5")
329
            .contentType(APPLICATION_JSON)
330
        )
331
            .andExpect(status().isOk())
332
            .andExpect(jsonPath("$.content", hasSize(5)))
333
            .andExpect(jsonPath("$.number", is(0)))
334
            .andExpect(jsonPath("$.size", is(5)))
335
            .andExpect(jsonPath("$.totalPages", is(2)))
336
            .andExpect(jsonPath("$.totalElements", is(9)));
337
    }
338

339
    @Test
340
    public void updateArticleTitle() throws Exception {
341
        ArticleUpdateDto articleUpdateDto = new ArticleUpdateDto();
342
        articleUpdateDto.setTitle("Some tittle value");
343

344
        mockMvc.perform(patch("/api/v1/articles/2")
345
            .contentType(APPLICATION_JSON)
346
            .content(json(articleUpdateDto))
347
        )
348
            .andExpect(status().isOk());
349
    }
350

351
    @Test
352
    public void updateArticleSummary() throws Exception {
353
        ArticleUpdateDto articleUpdateDto = new ArticleUpdateDto();
354
        articleUpdateDto.setSummary("Some summary value");
355

356
        mockMvc.perform(patch("/api/v1/articles/2")
357
            .contentType(APPLICATION_JSON)
358
            .content(json(articleUpdateDto))
359
        )
360
            .andExpect(status().isOk());
361
    }
362

363
    @Test
364
    public void updateArticleText() throws Exception {
365
        ArticleUpdateDto articleUpdateDto = new ArticleUpdateDto();
366
        articleUpdateDto.setText("Some text value");
367

368
        mockMvc.perform(patch("/api/v1/articles/2")
369
            .contentType(APPLICATION_JSON)
370
            .content(json(articleUpdateDto))
371
        )
372
            .andExpect(status().isOk());
373
    }
374

375
    @Test
376
    public void updateArticleMultipleFields() throws Exception {
377
        ArticleUpdateDto articleUpdateDto = new ArticleUpdateDto();
378
        articleUpdateDto.setSummary("Some summary value");
379
        articleUpdateDto.setText("Some text value");
380

381
        String message = mockMvc.perform(patch("/api/v1/articles/2")
382
            .contentType(APPLICATION_JSON)
383
            .content(json(articleUpdateDto))
384
        )
385
            .andExpect(status().isBadRequest())
386
            .andReturn().getResolvedException().getMessage();
387
        assertThat(message, containsString("Only one field should be modified at once"));
388
    }
389

390
    @Test
391
    public void updateAbsentArticle() throws Exception {
392
        ArticleUpdateDto articleUpdateDto = new ArticleUpdateDto();
393
        articleUpdateDto.setTitle("q");
394

395
        mockMvc.perform(patch("/api/v1/articles/123")
396
            .contentType(APPLICATION_JSON)
397
            .content(json(articleUpdateDto)))
398
            .andExpect(status().isNotFound());
399
    }
400

401
    @Test
402
    public void updateArticleWithEmptyTitle() throws Exception {
403
        ArticleUpdateDto articleUpdateDto = new ArticleUpdateDto();
404
        articleUpdateDto.setTitle("");
405

406
        String message = mockMvc.perform(patch("/api/v1/articles/2")
407
            .contentType(APPLICATION_JSON)
408
            .content(json(articleUpdateDto))
409
        )
410
            .andExpect(status().isBadRequest())
411
            .andReturn().getResolvedException().getMessage();
412
        assertThat(message, containsString("Title length must be between 1 and 100"));
413
    }
414

415
    @Test
416
    public void updateArticleWithTooLongTitle() throws Exception {
417
        ArticleUpdateDto articleUpdateDto = new ArticleUpdateDto();
418
        articleUpdateDto.setTitle(createStringWithLength(101));
419

420
        String message = mockMvc.perform(patch("/api/v1/articles/2")
421
            .contentType(APPLICATION_JSON)
422
            .content(json(articleUpdateDto))
423
        )
424
            .andExpect(status().isBadRequest())
425
            .andReturn().getResolvedException().getMessage();
426
        assertThat(message, containsString("Title length must be between 1 and 100"));
427
    }
428

429
    @Test
430
    public void updateArticleWithTooLongSummary() throws Exception {
431
        ArticleUpdateDto articleUpdateDto = new ArticleUpdateDto();
432
        articleUpdateDto.setSummary(createStringWithLength(260));
433

434
        String message = mockMvc.perform(patch("/api/v1/articles/2")
435
            .contentType(APPLICATION_JSON)
436
            .content(json(articleUpdateDto))
437
        )
438
            .andExpect(status().isBadRequest())
439
            .andReturn().getResolvedException().getMessage();
440
        assertThat(message, containsString("Summary length shouldn't be greater than 255"));
441
    }
442

443
    @Test
444
    public void updateArticleWithEmptyText() throws Exception {
445
        ArticleUpdateDto articleUpdateDto = new ArticleUpdateDto();
446
        articleUpdateDto.setText("");
447

448
        String message = mockMvc.perform(patch("/api/v1/articles/2")
449
            .contentType(APPLICATION_JSON)
450
            .content(json(articleUpdateDto))
451
        )
452
            .andExpect(status().isBadRequest())
453
            .andReturn().getResolvedException().getMessage();
454
        assertThat(message, containsString("Text length should be 1 at least"));
455
    }
456

457
    private String json(Object o) throws IOException {
458
        return objectMapper.writeValueAsString(o);
459
    }
460

461
    private String createStringWithLength(int length) {
462
        StringBuilder builder = new StringBuilder();
463
        for (int index = 0; index < length; index++) {
464
            builder.append("a");
465
        }
466
        return builder.toString();
467
    }
468
}
469

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.