-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathCustomerControllerTest.java
More file actions
315 lines (259 loc) · 14.9 KB
/
Copy pathCustomerControllerTest.java
File metadata and controls
315 lines (259 loc) · 14.9 KB
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
package com.ainigma100.customerapi.controller;
import com.ainigma100.customerapi.dto.CustomerDTO;
import com.ainigma100.customerapi.dto.CustomerEmailUpdateDTO;
import com.ainigma100.customerapi.dto.CustomerRequestDTO;
import com.ainigma100.customerapi.dto.CustomerSearchCriteriaDTO;
import com.ainigma100.customerapi.enums.Status;
import com.ainigma100.customerapi.mapper.CustomerMapper;
import com.ainigma100.customerapi.security.config.SecurityDevMockConfig;
import com.ainigma100.customerapi.service.CustomerService;
import tools.jackson.databind.ObjectMapper;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc;
import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest;
import org.springframework.context.annotation.Import;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.http.MediaType;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.bean.override.mockito.MockitoBean;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import java.time.LocalDate;
import java.util.Collections;
import java.util.List;
import static org.hamcrest.CoreMatchers.is;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.willDoNothing;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
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.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/*
* @WebMvcTest annotation will load all the components required
* to test the Controller layer. It will not load the service or repository layer components.
*
* Authentication mirrors the running application: SecurityDevMockConfig contributes a mock
* JwtDecoder that turns "admin-token"/"user-token" into the matching roles, so each request
* sends a Bearer token and exercises the real oauth2 resource server + AzureRoleConverter path.
*/
@WebMvcTest(CustomerController.class)
@AutoConfigureMockMvc // keep security filters enabled
@Tag("unit")
@ActiveProfiles("test")
@Import(SecurityDevMockConfig.class)
class CustomerControllerTest {
private static final String USER_TOKEN = "Bearer user-token";
private static final String ADMIN_TOKEN = "Bearer admin-token";
private static final String NO_ROLES_TOKEN = "Bearer no-roles-token";
@Autowired
private ObjectMapper objectMapper;
@Autowired
private MockMvc mockMvc;
@MockitoBean
private CustomerService customerService;
@MockitoBean
private CustomerMapper customerMapper;
private CustomerRequestDTO customerRequestDTO;
private CustomerDTO customerDTO;
private CustomerSearchCriteriaDTO customerSearchCriteriaDTO;
@BeforeEach
void setUp() {
customerRequestDTO = new CustomerRequestDTO();
customerRequestDTO.setFirstName("John");
customerRequestDTO.setLastName("Wick");
customerRequestDTO.setEmail("jwick@tester.com");
customerRequestDTO.setPhoneNumber("0123456789");
customerRequestDTO.setDateOfBirth(LocalDate.now().minusYears(18));
customerDTO = new CustomerDTO();
customerDTO.setId(1L);
customerDTO.setFirstName("John");
customerDTO.setLastName("Wick");
customerDTO.setEmail("jwick@tester.com");
customerDTO.setPhoneNumber("0123456789");
customerDTO.setDateOfBirth(LocalDate.now().minusYears(18));
customerSearchCriteriaDTO = new CustomerSearchCriteriaDTO();
customerSearchCriteriaDTO.setPage(0);
customerSearchCriteriaDTO.setSize(10);
}
@Test
void givenCustomerDTO_whenCreateCustomer_thenReturnCustomerDTO() throws Exception {
// given - precondition or setup
given(customerMapper.customerRequestDTOToCustomerDTO(any(CustomerRequestDTO.class)))
.willReturn(customerDTO);
given(customerService.createCustomer(any(CustomerDTO.class))).willReturn(customerDTO);
// when - action or behaviour that we are going to test
ResultActions response = mockMvc.perform(post("/api/v1/customers").with(csrf()) // add CSRF token at usage; harmless for stateless JWT
.header("Authorization", USER_TOKEN)
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(customerRequestDTO)));
// then - verify the output
response.andDo(print())
// verify the status code that is returned
.andExpect(status().isCreated())
// verify the Location header
.andExpect(MockMvcResultMatchers.header().string("Location", Matchers.endsWith("/api/v1/customers/1")))
// verify the actual returned value and the expected value
// $ - root member of a JSON structure whether it is an object or array
.andExpect(jsonPath("$.status", is(Status.SUCCESS.getValue())))
.andExpect(jsonPath("$.results.id", is(1)))
.andExpect(jsonPath("$.results.firstName", is("John")))
.andExpect(jsonPath("$.results.lastName", is("Wick")))
.andExpect(jsonPath("$.results.email", is("jwick@tester.com")))
.andExpect(jsonPath("$.results.phoneNumber", is("*******789")))
.andExpect(jsonPath("$.results.dateOfBirth", is(LocalDate.now().minusYears(18).toString())));
}
@Test
void givenCustomerDTO_whenGetCustomerById_thenReturnCustomerDTO() throws Exception {
// given - precondition or setup
given(customerService.getCustomerById(any(Long.class))).willReturn(customerDTO);
// when - action or behaviour that we are going to test
ResultActions response = mockMvc.perform(get("/api/v1/customers/{id}", 1L)
.header("Authorization", USER_TOKEN)
.contentType(MediaType.APPLICATION_JSON));
// then - verify the output
response.andDo(print())
// verify the status code that is returned
.andExpect(status().isOk())
// verify the actual returned value and the expected value
// $ - root member of a JSON structure whether it is an object or array
.andExpect(jsonPath("$.status", is(Status.SUCCESS.getValue())))
.andExpect(jsonPath("$.results.id", is(1)))
.andExpect(jsonPath("$.results.firstName", is("John")))
.andExpect(jsonPath("$.results.lastName", is("Wick")))
.andExpect(jsonPath("$.results.email", is("jwick@tester.com")))
.andExpect(jsonPath("$.results.phoneNumber", is("*******789")))
.andExpect(jsonPath("$.results.dateOfBirth", is(LocalDate.now().minusYears(18).toString())));
}
@Test
void givenCustomerDTO_whenUpdateCustomer_thenReturnCustomerDTO() throws Exception {
// given - precondition or setup
given(customerMapper.customerRequestDTOToCustomerDTO(any(CustomerRequestDTO.class)))
.willReturn(customerDTO);
given(customerService.updateCustomer(any(Long.class), any(CustomerDTO.class))).willReturn(customerDTO);
// when - action or behaviour that we are going to test
ResultActions response = mockMvc.perform(put("/api/v1/customers/{id}", 1L).with(csrf()) // add CSRF token at usage; harmless for stateless JWT
.header("Authorization", USER_TOKEN)
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(customerRequestDTO)));
// then - verify the output
response.andDo(print())
// verify the status code that is returned
.andExpect(status().isOk())
// verify the actual returned value and the expected value
// $ - root member of a JSON structure whether it is an object or array
.andExpect(jsonPath("$.status", is(Status.SUCCESS.getValue())))
.andExpect(jsonPath("$.results.id", is(1)))
.andExpect(jsonPath("$.results.firstName", is("John")))
.andExpect(jsonPath("$.results.lastName", is("Wick")))
.andExpect(jsonPath("$.results.email", is("jwick@tester.com")))
.andExpect(jsonPath("$.results.phoneNumber", is("*******789")))
.andExpect(jsonPath("$.results.dateOfBirth", is(LocalDate.now().minusYears(18).toString())));
}
@Test
void givenCustomerEmailUpdateDTO_whenUpdateCustomerEmail_thenReturnCustomerDTO() throws Exception {
// given - precondition or setup
CustomerEmailUpdateDTO customerEmailUpdateDTO = new CustomerEmailUpdateDTO();
customerEmailUpdateDTO.setEmail("loco@gmail.com");
customerDTO.setEmail(customerEmailUpdateDTO.getEmail());
given(customerService.updateCustomerEmail(any(Long.class), any(CustomerEmailUpdateDTO.class)))
.willReturn(customerDTO);
// when - action or behaviour that we are going to test
ResultActions response = mockMvc.perform(patch("/api/v1/customers/{id}/email", 1L).with(csrf()) // add CSRF token at usage; harmless for stateless JWT
.header("Authorization", USER_TOKEN)
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(customerEmailUpdateDTO)));
// then - verify the output
response.andDo(print())
// verify the status code that is returned
.andExpect(status().isOk())
// verify the actual returned value and the expected value
// $ - root member of a JSON structure whether it is an object or array
.andExpect(jsonPath("$.status", is(Status.SUCCESS.getValue())))
.andExpect(jsonPath("$.results.id", is(1)))
.andExpect(jsonPath("$.results.firstName", is("John")))
.andExpect(jsonPath("$.results.lastName", is("Wick")))
.andExpect(jsonPath("$.results.email", is("loco@gmail.com")))
.andExpect(jsonPath("$.results.phoneNumber", is("*******789")))
.andExpect(jsonPath("$.results.dateOfBirth", is(LocalDate.now().minusYears(18).toString())));
}
@Test
void givenCustomerDTO_whenDeleteCustomer_thenReturnCustomerDTO() throws Exception {
// given - precondition or setup
willDoNothing().given(customerService).deleteCustomer(any(Long.class));
// when - action or behaviour that we are going to test
ResultActions response = mockMvc.perform(delete("/api/v1/customers/{id}", 1L).with(csrf()) // add CSRF token at usage; harmless for stateless JWT
.header("Authorization", ADMIN_TOKEN)
.contentType(MediaType.APPLICATION_JSON));
// then - verify the output
response.andDo(print())
// verify the status code that is returned
.andExpect(status().isOk())
// verify the actual returned value and the expected value
// $ - root member of a JSON structure whether it is an object or array
.andExpect(jsonPath("$.status", is(Status.SUCCESS.getValue())));
}
@Test
void givenUserRole_whenDeleteCustomer_thenForbidden() throws Exception {
// when - a USER attempts to delete
mockMvc.perform(delete("/api/v1/customers/{id}", 1L)
.header("Authorization", USER_TOKEN)
.contentType(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(status().isForbidden());
}
@Test
void givenCustomerSearchCriteriaDTO_whenGetAllCustomersUsingPagination_thenReturnCustomerDTOPage() throws Exception {
// given - precondition or setup
List<CustomerDTO> customerDTOList = Collections.singletonList(customerDTO);
Page<CustomerDTO> customerDTOPage = new PageImpl<>(customerDTOList);
given(customerService.getAllCustomersUsingPagination(any(CustomerSearchCriteriaDTO.class)))
.willReturn(customerDTOPage);
// when - action or behaviour that we are going to test
ResultActions response = mockMvc.perform(post("/api/v1/customers/search").with(csrf()) // add CSRF token at usage; harmless for stateless JWT
.header("Authorization", USER_TOKEN)
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(customerSearchCriteriaDTO)));
// then - verify the output
response.andDo(print())
// verify the status code that is returned
.andExpect(status().isOk())
// verify the actual returned value and the expected value
// $ - root member of a JSON structure whether it is an object or array
.andExpect(jsonPath("$.status", is(Status.SUCCESS.getValue())))
.andExpect(jsonPath("$.results.content.size()", is(customerDTOList.size())))
.andExpect(jsonPath("$.results.content[0].firstName", is(customerDTOList.get(0).getFirstName())))
.andExpect(jsonPath("$.results.content[0].lastName", is(customerDTOList.get(0).getLastName())))
.andExpect(jsonPath("$.results.content[0].email", is(customerDTOList.get(0).getEmail())))
.andExpect(jsonPath("$.results.content[0].phoneNumber", is("*******789")));
}
@Test
void givenNoAuth_whenGetCustomerById_thenUnauthorized() throws Exception {
// given - precondition or setup
// no Authorization header is sent
// when - action or behaviour that we are going to test
ResultActions response = mockMvc.perform(get("/api/v1/customers/{id}", 1L)
.contentType(MediaType.APPLICATION_JSON));
// then - verify the output
response.andDo(print())
.andExpect(status().isUnauthorized());
}
@Test
void givenAuthWithoutRequiredRoles_whenGetCustomerById_thenForbidden() throws Exception {
// given - a valid token that carries no ADMIN/USER role
// when - action or behaviour that we are going to test
ResultActions response = mockMvc.perform(get("/api/v1/customers/{id}", 1L)
.header("Authorization", NO_ROLES_TOKEN)
.contentType(MediaType.APPLICATION_JSON));
// then - verify the output
response.andDo(print())
.andExpect(status().isForbidden());
}
}