spring-boot-2-template

Форк
0
440 строк · 16.8 Кб
1
package by.andd3dfx.templateapp.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.templateapp.IntegrationTestInitializer;
18
import by.andd3dfx.templateapp.dto.ArticleDto;
19
import by.andd3dfx.templateapp.dto.ArticleUpdateDto;
20
import com.fasterxml.jackson.databind.ObjectMapper;
21
import java.io.IOException;
22
import java.time.LocalDateTime;
23
import org.junit.jupiter.api.BeforeEach;
24
import org.junit.jupiter.api.Test;
25
import org.springframework.beans.factory.annotation.Autowired;
26
import org.springframework.boot.test.context.SpringBootTest;
27
import org.springframework.mock.http.MockHttpOutputMessage;
28
import org.springframework.test.context.ContextConfiguration;
29
import org.springframework.test.context.web.WebAppConfiguration;
30
import org.springframework.test.web.servlet.MockMvc;
31
import org.springframework.web.context.WebApplicationContext;
32

33
@ContextConfiguration(initializers = IntegrationTestInitializer.class)
34
@SpringBootTest
35
@WebAppConfiguration
36
class ArticleControllerTest {
37

38
    private MockMvc mockMvc;
39

40
    @Autowired
41
    private WebApplicationContext webApplicationContext;
42
    @Autowired
43
    private ObjectMapper objectMapper;
44

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

51
    @Test
52
    public void createArticle() throws Exception {
53
        ArticleDto articleDto = ArticleDto.builder()
54
                .title("Some tittle value")
55
                .summary("Some summary value")
56
                .text("Some text")
57
                .author("Some author")
58
                .build();
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", is(articleDto.getAuthor())))
70
            .andExpect(jsonPath("$.dateCreated", notNullValue()))
71
            .andExpect(jsonPath("$.dateUpdated", notNullValue()));
72
    }
73

74
    @Test
75
    public void createArticleWithIdPopulated() throws Exception {
76
        ArticleDto articleDto = ArticleDto.builder()
77
                .id(123L)
78
                .title("Some tittle value")
79
                .summary("Some summary value")
80
                .text("Some text")
81
                .author("Some author")
82
                .build();
83

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

93
    @Test
94
    public void createArticleWithoutTitle() throws Exception {
95
        ArticleDto articleDto = new ArticleDto();
96
        articleDto.setSummary("Some summary value");
97
        articleDto.setText("Some text");
98
        articleDto.setAuthor("Some author");
99

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

109
    @Test
110
    public void createArticleWithEmptyTitle() throws Exception {
111
        ArticleDto articleDto = new ArticleDto();
112
        articleDto.setTitle("");
113
        articleDto.setSummary("Some summary value");
114
        articleDto.setText("Some text");
115
        articleDto.setAuthor("Some author");
116

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

126
    @Test
127
    public void createArticleWithTooLongTitle() throws Exception {
128
        ArticleDto articleDto = new ArticleDto();
129
        articleDto.setTitle(createStringWithLength(101));
130
        articleDto.setSummary("Some summary value");
131
        articleDto.setText("Some text");
132
        articleDto.setAuthor("Some author");
133

134
        String message = mockMvc.perform(post("/api/v1/articles")
135
            .contentType(APPLICATION_JSON)
136
            .content(json(articleDto))
137
        )
138
            .andExpect(status().isBadRequest())
139
            .andReturn().getResolvedException().getMessage();
140
        assertThat(message, containsString("Title length must be between 1 and 100"));
141
    }
142

143
    @Test
144
    public void createArticleWithTooLongSummary() throws Exception {
145
        ArticleDto articleDto = new ArticleDto();
146
        articleDto.setTitle("Some title");
147
        articleDto.setSummary(createStringWithLength(260));
148
        articleDto.setText("Some text");
149
        articleDto.setAuthor("Some author");
150

151
        String message = mockMvc.perform(post("/api/v1/articles")
152
            .contentType(APPLICATION_JSON)
153
            .content(json(articleDto))
154
        )
155
            .andExpect(status().isBadRequest())
156
            .andReturn().getResolvedException().getMessage();
157
        assertThat(message, containsString("Summary length shouldn't be greater than 255"));
158
    }
159

160
    @Test
161
    public void createArticleWithoutText() throws Exception {
162
        ArticleDto articleDto = ArticleDto.builder()
163
                .title("Some title")
164
                .summary("Some summary value")
165
                .author("Some author")
166
                .build();
167

168
        String message = mockMvc.perform(post("/api/v1/articles")
169
            .contentType(APPLICATION_JSON)
170
            .content(json(articleDto))
171
        )
172
            .andExpect(status().isBadRequest())
173
            .andReturn().getResolvedException().getMessage();
174
        assertThat(message, containsString("Text should be populated"));
175
    }
176

177
    @Test
178
    public void createArticleWithEmptyText() throws Exception {
179
        ArticleDto articleDto = new ArticleDto();
180
        articleDto.setTitle("Some title");
181
        articleDto.setSummary("Some summary value");
182
        articleDto.setText("");
183
        articleDto.setAuthor("Some author");
184

185
        String message = mockMvc.perform(post("/api/v1/articles")
186
            .contentType(APPLICATION_JSON)
187
            .content(json(articleDto))
188
        )
189
            .andExpect(status().isBadRequest())
190
            .andReturn().getResolvedException().getMessage();
191
        assertThat(message, containsString("Text length should be 1 at least"));
192
    }
193

194
    @Test
195
    public void createArticleWithoutAuthor() throws Exception {
196
        ArticleDto articleDto = new ArticleDto();
197
        articleDto.setTitle("Some title");
198
        articleDto.setSummary("Some summary value");
199
        articleDto.setText("Some text");
200

201
        String message = mockMvc.perform(post("/api/v1/articles")
202
            .contentType(APPLICATION_JSON)
203
            .content(json(articleDto))
204
        )
205
            .andExpect(status().isBadRequest())
206
            .andReturn().getResolvedException().getMessage();
207
        assertThat(message, containsString("Author should be populated"));
208
    }
209

210
    @Test
211
    public void createArticleWithDateCreatedPopulated() throws Exception {
212
        ArticleDto articleDto = new ArticleDto();
213
        articleDto.setTitle("Some tittle value");
214
        articleDto.setSummary("Some summary value");
215
        articleDto.setText("Some text");
216
        articleDto.setAuthor("Some author");
217
        articleDto.setDateCreated(LocalDateTime.now());
218

219
        String message = mockMvc.perform(post("/api/v1/articles")
220
            .contentType(APPLICATION_JSON)
221
            .content(json(articleDto))
222
        )
223
            .andExpect(status().isBadRequest())
224
            .andReturn().getResolvedException().getMessage();
225
        assertThat(message, containsString("DateCreated shouldn't be populated"));
226
    }
227

228
    @Test
229
    public void createArticleWithDateUpdatedPopulated() throws Exception {
230
        ArticleDto articleDto = new ArticleDto();
231
        articleDto.setTitle("Some tittle value");
232
        articleDto.setSummary("Some summary value");
233
        articleDto.setText("Some text");
234
        articleDto.setAuthor("Some author");
235
        articleDto.setDateUpdated(LocalDateTime.now());
236

237
        String message = mockMvc.perform(post("/api/v1/articles")
238
            .contentType(APPLICATION_JSON)
239
            .content(json(articleDto))
240
        )
241
            .andExpect(status().isBadRequest())
242
            .andReturn().getResolvedException().getMessage();
243
        assertThat(message, containsString("DateUpdated shouldn't be populated"));
244
    }
245

246
    @Test
247
    public void deleteArticle() throws Exception {
248
        mockMvc.perform(delete("/api/v1/articles/1")
249
            .contentType(APPLICATION_JSON)
250
        )
251
            .andExpect(status().isNoContent());
252
    }
253

254
    @Test
255
    public void deleteAbsentArticle() throws Exception {
256
        mockMvc.perform(delete("/api/v1/articles/9999")
257
            .contentType(APPLICATION_JSON))
258
            .andExpect(status().isNotFound());
259
    }
260

261
    @Test
262
    public void readArticle() throws Exception {
263
        mockMvc.perform(get("/api/v1/articles/1")
264
            .contentType(APPLICATION_JSON)
265
        )
266
            .andExpect(status().isOk())
267
            .andExpect(jsonPath("$.id", is(1)));
268
    }
269

270
    @Test
271
    public void readAbsentArticle() throws Exception {
272
        mockMvc.perform(get("/api/v1/articles/345")
273
            .contentType(APPLICATION_JSON))
274
            .andExpect(status().isNotFound());
275
    }
276

277
    @Test
278
    public void readArticles() throws Exception {
279
        mockMvc.perform(get("/api/v1/articles")
280
            .contentType(APPLICATION_JSON)
281
        )
282
            .andExpect(status().isOk())
283
            .andExpect(jsonPath("$.content", hasSize(10)))
284
            .andExpect(jsonPath("$.number", is(0)))
285
            .andExpect(jsonPath("$.size", is(50)))
286
            .andExpect(jsonPath("$.totalPages", is(1)))
287
            .andExpect(jsonPath("$.totalElements", is(10)));
288
    }
289

290
    @Test
291
    public void readArticlesWithPageSizeLimit() throws Exception {
292
        mockMvc.perform(get("/api/v1/articles")
293
            .param("size", "5")
294
            .contentType(APPLICATION_JSON)
295
        )
296
            .andExpect(status().isOk())
297
            .andExpect(jsonPath("$.content", hasSize(5)))
298
            .andExpect(jsonPath("$.number", is(0)))
299
            .andExpect(jsonPath("$.size", is(5)))
300
            .andExpect(jsonPath("$.totalPages", is(2)))
301
            .andExpect(jsonPath("$.totalElements", is(9)));
302
    }
303

304
    @Test
305
    public void updateArticleTitle() throws Exception {
306
        ArticleUpdateDto articleUpdateDto = ArticleUpdateDto.builder()
307
                .title("Some tittle value")
308
                .build();
309

310
        mockMvc.perform(patch("/api/v1/articles/2")
311
            .contentType(APPLICATION_JSON)
312
            .content(json(articleUpdateDto))
313
        )
314
            .andExpect(status().isOk());
315
    }
316

317
    @Test
318
    public void updateArticleSummary() throws Exception {
319
        ArticleUpdateDto articleUpdateDto = ArticleUpdateDto.builder()
320
                .summary("Some summary value")
321
                .build();
322

323
        mockMvc.perform(patch("/api/v1/articles/2")
324
            .contentType(APPLICATION_JSON)
325
            .content(json(articleUpdateDto))
326
        )
327
            .andExpect(status().isOk());
328
    }
329

330
    @Test
331
    public void updateArticleText() throws Exception {
332
        ArticleUpdateDto articleUpdateDto = new ArticleUpdateDto();
333
        articleUpdateDto.setText("Some text value");
334

335
        mockMvc.perform(patch("/api/v1/articles/2")
336
            .contentType(APPLICATION_JSON)
337
            .content(json(articleUpdateDto))
338
        )
339
            .andExpect(status().isOk());
340
    }
341

342
    @Test
343
    public void updateArticleMultipleFields() throws Exception {
344
        ArticleUpdateDto articleUpdateDto = new ArticleUpdateDto();
345
        articleUpdateDto.setSummary("Some summary value");
346
        articleUpdateDto.setText("Some text value");
347

348
        String message = mockMvc.perform(patch("/api/v1/articles/2")
349
            .contentType(APPLICATION_JSON)
350
            .content(json(articleUpdateDto))
351
        )
352
            .andExpect(status().isBadRequest())
353
            .andReturn().getResolvedException().getMessage();
354
        assertThat(message, containsString("Only one field should be modified at once"));
355
    }
356

357
    @Test
358
    public void updateAbsentArticle() throws Exception {
359
        ArticleUpdateDto articleUpdateDto = ArticleUpdateDto.builder()
360
                .title("q")
361
                .build();
362

363
        mockMvc.perform(patch("/api/v1/articles/123")
364
            .contentType(APPLICATION_JSON)
365
            .content(json(articleUpdateDto)))
366
            .andExpect(status().isNotFound());
367
    }
368

369
    @Test
370
    public void updateArticleWithEmptyTitle() throws Exception {
371
        ArticleUpdateDto articleUpdateDto = ArticleUpdateDto.builder()
372
                .title("")
373
                .build();
374

375
        String message = mockMvc.perform(patch("/api/v1/articles/2")
376
            .contentType(APPLICATION_JSON)
377
            .content(json(articleUpdateDto))
378
        )
379
            .andExpect(status().isBadRequest())
380
            .andReturn().getResolvedException().getMessage();
381
        assertThat(message, containsString("Title length must be between 1 and 100"));
382
    }
383

384
    @Test
385
    public void updateArticleWithTooLongTitle() throws Exception {
386
        ArticleUpdateDto articleUpdateDto = ArticleUpdateDto.builder()
387
                .title(createStringWithLength(101))
388
                .build();
389

390
        String message = mockMvc.perform(patch("/api/v1/articles/2")
391
            .contentType(APPLICATION_JSON)
392
            .content(json(articleUpdateDto))
393
        )
394
            .andExpect(status().isBadRequest())
395
            .andReturn().getResolvedException().getMessage();
396
        assertThat(message, containsString("Title length must be between 1 and 100"));
397
    }
398

399
    @Test
400
    public void updateArticleWithTooLongSummary() throws Exception {
401
        ArticleUpdateDto articleUpdateDto = ArticleUpdateDto.builder()
402
                .summary(createStringWithLength(260))
403
                .build();
404

405
        String message = mockMvc.perform(patch("/api/v1/articles/2")
406
            .contentType(APPLICATION_JSON)
407
            .content(json(articleUpdateDto))
408
        )
409
            .andExpect(status().isBadRequest())
410
            .andReturn().getResolvedException().getMessage();
411
        assertThat(message, containsString("Summary length shouldn't be greater than 255"));
412
    }
413

414
    @Test
415
    public void updateArticleWithEmptyText() throws Exception {
416
        ArticleUpdateDto articleUpdateDto = ArticleUpdateDto.builder()
417
                .text("")
418
                .build();
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("Text length should be 1 at least"));
427
    }
428

429
    private String json(Object o) throws IOException {
430
        return objectMapper.writeValueAsString(o);
431
    }
432

433
    private String createStringWithLength(int length) {
434
        StringBuilder builder = new StringBuilder();
435
        for (int index = 0; index < length; index++) {
436
            builder.append("a");
437
        }
438
        return builder.toString();
439
    }
440
}
441

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

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

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

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