-
Notifications
You must be signed in to change notification settings - Fork 288
/
EventControllerTests.java
411 lines (365 loc) · 18.9 KB
/
EventControllerTests.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
package me.whiteship.demoinfleanrestapi.events;
import me.whiteship.demoinfleanrestapi.accounts.Account;
import me.whiteship.demoinfleanrestapi.accounts.AccountRepository;
import me.whiteship.demoinfleanrestapi.accounts.AccountRole;
import me.whiteship.demoinfleanrestapi.accounts.AccountService;
import me.whiteship.demoinfleanrestapi.common.AppProperties;
import me.whiteship.demoinfleanrestapi.common.BaseTest;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.hateoas.MediaTypes;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.security.oauth2.common.util.Jackson2JsonParser;
import org.springframework.test.web.servlet.ResultActions;
import java.time.LocalDateTime;
import java.util.Set;
import java.util.stream.IntStream;
import static org.springframework.restdocs.headers.HeaderDocumentation.*;
import static org.springframework.restdocs.hypermedia.HypermediaDocumentation.linkWithRel;
import static org.springframework.restdocs.hypermedia.HypermediaDocumentation.links;
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document;
import static org.springframework.restdocs.payload.PayloadDocumentation.*;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.httpBasic;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
public class EventControllerTests extends BaseTest {
@Autowired
EventRepository eventRepository;
@Autowired
AccountService accountService;
@Autowired
AccountRepository accountRepository;
@Autowired
AppProperties appProperties;
@BeforeEach
public void setUp() {
this.eventRepository.deleteAll();
this.accountRepository.deleteAll();
}
@Test
@DisplayName("정상적으로 이벤트를 생성하는 테스트")
public void createEvent() throws Exception {
EventDto event = EventDto.builder()
.name("Spring")
.description("REST API Development with Spring")
.beginEnrollmentDateTime(LocalDateTime.of(2018, 11, 23, 14, 21))
.closeEnrollmentDateTime(LocalDateTime.of(2018, 11, 24, 14, 21))
.beginEventDateTime(LocalDateTime.of(2018, 11, 25, 14, 21))
.endEventDateTime(LocalDateTime.of(2018, 11, 26, 14, 21))
.basePrice(100)
.maxPrice(200)
.limitOfEnrollment(100)
.location("강남역 D2 스타텁 팩토리")
.build();
mockMvc.perform(post("/api/events/")
.header(HttpHeaders.AUTHORIZATION, getBearerToken(true))
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaTypes.HAL_JSON)
.content(objectMapper.writeValueAsString(event)))
.andDo(print())
.andExpect(status().isCreated())
.andExpect(jsonPath("id").exists())
.andExpect(header().exists(HttpHeaders.LOCATION))
.andExpect(header().string(HttpHeaders.CONTENT_TYPE, MediaTypes.HAL_JSON_VALUE))
.andExpect(jsonPath("free").value(false))
.andExpect(jsonPath("offline").value(true))
.andExpect(jsonPath("eventStatus").value(EventStatus.DRAFT.name()))
.andDo(document("create-event",
links(
linkWithRel("self").description("link to self"),
linkWithRel("query-events").description("link to query events"),
linkWithRel("update-event").description("link to update an existing event"),
linkWithRel("profile").description("link to update an existing event")
),
requestHeaders(
headerWithName(HttpHeaders.ACCEPT).description("accept header"),
headerWithName(HttpHeaders.CONTENT_TYPE).description("content type header")
),
requestFields(
fieldWithPath("name").description("Name of new event"),
fieldWithPath("description").description("description of new event"),
fieldWithPath("beginEnrollmentDateTime").description("date time of begin of new event"),
fieldWithPath("closeEnrollmentDateTime").description("date time of close of new event"),
fieldWithPath("beginEventDateTime").description("date time of begin of new event"),
fieldWithPath("endEventDateTime").description("date time of end of new event"),
fieldWithPath("location").description("location of new event"),
fieldWithPath("basePrice").description("base price of new event"),
fieldWithPath("maxPrice").description("max price of new event"),
fieldWithPath("limitOfEnrollment").description("limit of enrolmment")
),
responseHeaders(
headerWithName(HttpHeaders.LOCATION).description("Location header"),
headerWithName(HttpHeaders.CONTENT_TYPE).description("Content type")
),
relaxedResponseFields(
fieldWithPath("id").description("identifier of new event"),
fieldWithPath("name").description("Name of new event"),
fieldWithPath("description").description("description of new event"),
fieldWithPath("beginEnrollmentDateTime").description("date time of begin of new event"),
fieldWithPath("closeEnrollmentDateTime").description("date time of close of new event"),
fieldWithPath("beginEventDateTime").description("date time of begin of new event"),
fieldWithPath("endEventDateTime").description("date time of end of new event"),
fieldWithPath("location").description("location of new event"),
fieldWithPath("basePrice").description("base price of new event"),
fieldWithPath("maxPrice").description("max price of new event"),
fieldWithPath("limitOfEnrollment").description("limit of enrolmment"),
fieldWithPath("free").description("it tells if this event is free or not"),
fieldWithPath("offline").description("it tells if this event is offline event or not"),
fieldWithPath("eventStatus").description("event status"),
fieldWithPath("_links.self.href").description("link to self"),
fieldWithPath("_links.query-events.href").description("link to query event list"),
fieldWithPath("_links.update-event.href").description("link to update existing event"),
fieldWithPath("_links.profile.href").description("link to profile")
)
))
;
}
private String getBearerToken(boolean needToCreateAccount) throws Exception {
return "Bearer " + getAccessToken(needToCreateAccount);
}
private String getAccessToken(boolean needToCreateAccount) throws Exception {
// Given
if (needToCreateAccount) {
createAccount();
}
ResultActions perform = this.mockMvc.perform(post("/oauth/token")
.with(httpBasic(appProperties.getClientId(), appProperties.getClientSecret()))
.param("username", appProperties.getUserUsername())
.param("password", appProperties.getUserPassword())
.param("grant_type", "password"));
var responseBody = perform.andReturn().getResponse().getContentAsString();
Jackson2JsonParser parser = new Jackson2JsonParser();
return parser.parseMap(responseBody).get("access_token").toString();
}
private Account createAccount() {
Account keesun = Account.builder()
.email(appProperties.getUserUsername())
.password(appProperties.getUserPassword())
.roles(Set.of(AccountRole.ADMIN, AccountRole.USER))
.build();
return this.accountService.saveAccount(keesun);
}
@Test
@DisplayName("입력 받을 수 없는 값을 사용한 경우에 에러가 발생하는 테스트")
public void createEvent_Bad_Request() throws Exception {
Event event = Event.builder()
.id(100)
.name("Spring")
.description("REST API Development with Spring")
.beginEnrollmentDateTime(LocalDateTime.of(2018, 11, 23, 14, 21))
.closeEnrollmentDateTime(LocalDateTime.of(2018, 11, 24, 14, 21))
.beginEventDateTime(LocalDateTime.of(2018, 11, 25, 14, 21))
.endEventDateTime(LocalDateTime.of(2018, 11, 26, 14, 21))
.basePrice(100)
.maxPrice(200)
.limitOfEnrollment(100)
.location("강남역 D2 스타텁 팩토리")
.free(true)
.offline(false)
.eventStatus(EventStatus.PUBLISHED)
.build();
mockMvc.perform(post("/api/events/")
.header(HttpHeaders.AUTHORIZATION, getBearerToken(true))
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaTypes.HAL_JSON)
.content(objectMapper.writeValueAsString(event)))
.andDo(print())
.andExpect(status().isBadRequest())
;
}
@Test
@DisplayName("입력 값이 비어있는 경우에 에러가 발생하는 테스트")
public void createEvent_Bad_Request_Empty_Input() throws Exception {
EventDto eventDto = EventDto.builder().build();
this.mockMvc.perform(post("/api/events")
.header(HttpHeaders.AUTHORIZATION, getBearerToken(true))
.contentType(MediaType.APPLICATION_JSON)
.content(this.objectMapper.writeValueAsString(eventDto)))
.andExpect(status().isBadRequest());
}
@Test
@DisplayName("입력 값이 잘못된 경우에 에러가 발생하는 테스트")
public void createEvent_Bad_Request_Wrong_Input() throws Exception {
EventDto eventDto = EventDto.builder()
.name("Spring")
.description("REST API Development with Spring")
.beginEnrollmentDateTime(LocalDateTime.of(2018, 11, 26, 14, 21))
.closeEnrollmentDateTime(LocalDateTime.of(2018, 11, 25, 14, 21))
.beginEventDateTime(LocalDateTime.of(2018, 11, 24, 14, 21))
.endEventDateTime(LocalDateTime.of(2018, 11, 23, 14, 21))
.basePrice(10000)
.maxPrice(200)
.limitOfEnrollment(100)
.location("강남역 D2 스타텁 팩토리")
.build();
this.mockMvc.perform(post("/api/events")
.header(HttpHeaders.AUTHORIZATION, getBearerToken(true))
.contentType(MediaType.APPLICATION_JSON)
.content(this.objectMapper.writeValueAsString(eventDto)))
.andDo(print())
.andExpect(status().isBadRequest())
.andExpect(jsonPath("content[0].objectName").exists())
.andExpect(jsonPath("content[0].defaultMessage").exists())
.andExpect(jsonPath("content[0].code").exists())
.andExpect(jsonPath("_links.index").exists())
;
}
@Test
@DisplayName("30개의 이벤트를 10개씩 두번째 페이지 조회하기")
public void queryEvents() throws Exception {
// Given
IntStream.range(0, 30).forEach(this::generateEvent);
// When & Then
this.mockMvc.perform(get("/api/events")
.param("page", "1")
.param("size", "10")
.param("sort", "name,DESC"))
.andDo(print())
.andExpect(status().isOk())
.andExpect(jsonPath("page").exists())
.andExpect(jsonPath("_embedded.eventList[0]._links.self").exists())
.andExpect(jsonPath("_links.self").exists())
.andExpect(jsonPath("_links.profile").exists())
.andDo(document("query-events"))
;
}
@Test
@DisplayName("30개의 이벤트를 10개씩 두번째 페이지 조회하기")
public void queryEventsWithAuthentication() throws Exception {
// Given
IntStream.range(0, 30).forEach(this::generateEvent);
// When & Then
this.mockMvc.perform(get("/api/events")
.header(HttpHeaders.AUTHORIZATION, getBearerToken(true))
.param("page", "1")
.param("size", "10")
.param("sort", "name,DESC"))
.andDo(print())
.andExpect(status().isOk())
.andExpect(jsonPath("page").exists())
.andExpect(jsonPath("_embedded.eventList[0]._links.self").exists())
.andExpect(jsonPath("_links.self").exists())
.andExpect(jsonPath("_links.profile").exists())
.andExpect(jsonPath("_links.create-event").exists())
.andDo(document("query-events"))
;
}
@Test
@DisplayName("기존의 이벤트를 하나 조죄하기")
public void getEvent() throws Exception {
// Given
Account account = this.createAccount();
Event event = this.generateEvent(100, account);
// When & Then
this.mockMvc.perform(get("/api/events/{id}", event.getId()))
.andExpect(status().isOk())
.andExpect(jsonPath("name").exists())
.andExpect(jsonPath("id").exists())
.andExpect(jsonPath("_links.self").exists())
.andExpect(jsonPath("_links.profile").exists())
.andDo(document("get-an-event"))
;
}
@Test
@DisplayName("없는 이벤트는 조회했을 때 404 응답받기")
public void getEvent404() throws Exception {
// When & Then
this.mockMvc.perform(get("/api/events/11883"))
.andExpect(status().isNotFound());
}
@Test
@DisplayName("이벤트를 정상적으로 수정하기")
public void updateEvent() throws Exception {
// Given
Account account = this.createAccount();
Event event = this.generateEvent(200, account);
EventDto eventDto = this.modelMapper.map(event, EventDto.class);
String eventName = "Updated Event";
eventDto.setName(eventName);
// When & Then
this.mockMvc.perform(put("/api/events/{id}", event.getId())
.header(HttpHeaders.AUTHORIZATION, getBearerToken(false))
.contentType(MediaType.APPLICATION_JSON)
.content(this.objectMapper.writeValueAsString(eventDto)))
.andDo(print())
.andExpect(status().isOk())
.andExpect(jsonPath("name").value(eventName))
.andExpect(jsonPath("_links.self").exists())
.andDo(document("update-event"))
;
}
@Test
@DisplayName("입력값이 비어있는 경우에 이벤트 수정 실패")
public void updateEvent400_Empty() throws Exception {
// Given
Event event = this.generateEvent(200);
EventDto eventDto = new EventDto();
// When & Then
this.mockMvc.perform(put("/api/events/{id}", event.getId())
.header(HttpHeaders.AUTHORIZATION, getBearerToken(true))
.contentType(MediaType.APPLICATION_JSON)
.content(this.objectMapper.writeValueAsString(eventDto)))
.andDo(print())
.andExpect(status().isBadRequest());
}
@Test
@DisplayName("입력값이 잘못된 경우에 이벤트 수정 실패")
public void updateEvent400_Wrong() throws Exception {
// Given
Event event = this.generateEvent(200);
EventDto eventDto = this.modelMapper.map(event, EventDto.class);
eventDto.setBasePrice(20000);
eventDto.setMaxPrice(1000);
// When & Then
this.mockMvc.perform(put("/api/events/{id}", event.getId())
.header(HttpHeaders.AUTHORIZATION, getBearerToken(true))
.contentType(MediaType.APPLICATION_JSON)
.content(this.objectMapper.writeValueAsString(eventDto)))
.andDo(print())
.andExpect(status().isBadRequest());
}
@Test
@DisplayName("존재하지 않는 이벤트 수정 실패")
public void updateEvent404() throws Exception {
// Given
Event event = this.generateEvent(200);
EventDto eventDto = this.modelMapper.map(event, EventDto.class);
// When & Then
this.mockMvc.perform(put("/api/events/123123")
.header(HttpHeaders.AUTHORIZATION, getBearerToken(true))
.contentType(MediaType.APPLICATION_JSON)
.content(this.objectMapper.writeValueAsString(eventDto)))
.andDo(print())
.andExpect(status().isNotFound());
}
private Event generateEvent(int index, Account account) {
Event event = buildEvent(index);
event.setManager(account);
return this.eventRepository.save(event);
}
private Event generateEvent(int index) {
Event event = buildEvent(index);
return this.eventRepository.save(event);
}
private Event buildEvent(int index) {
return Event.builder()
.name("event " + index)
.description("test event")
.beginEnrollmentDateTime(LocalDateTime.of(2018, 11, 23, 14, 21))
.closeEnrollmentDateTime(LocalDateTime.of(2018, 11, 24, 14, 21))
.beginEventDateTime(LocalDateTime.of(2018, 11, 25, 14, 21))
.endEventDateTime(LocalDateTime.of(2018, 11, 26, 14, 21))
.basePrice(100)
.maxPrice(200)
.limitOfEnrollment(100)
.location("강남역 D2 스타텁 팩토리")
.free(false)
.offline(true)
.eventStatus(EventStatus.DRAFT)
.build();
}
}