I have an issue with REST Controller testing:
@WebMvcTest(PersonController.class)
public class Testing {
@MockBean
PersonService personService;
@MockBean
JwtAuthenticationFilter jwtAuthenticationFilter;
@Autowired
ObjectMapper objectMapper;
@Autowired
MockMvc mockMvc;
@Test
@WithMockUser(username="tester")
void test() throws Exception {
PersonGetDTO person1 = new PersonGetDTO(1L,
"FirstName1",
"LastName1",
"img1.png",
LocalDateTime.of(LocalDate.of(2000, 01, 01), LocalTime.of(00, 00))
);
PersonGetDTO person2 = new PersonGetDTO(2L,
"FirstName2",
"LastName2",
"img2.png",
LocalDateTime.of(LocalDate.of(2000, 01, 01), LocalTime.of(00, 01))
);
List<PersonGetDTO> personList = new ArrayList<>();
personList.add(person1);
personList.add(person2);
Pageable pageable = Pageable.unpaged();
Page<PersonGetDTO> persons = new PageImpl<>(personsList, pageable, personList.size());
when(personService.getPersons(Mockito.any(), Mockito.any())).thenReturn(ResponseEntity.ok(persons));
mockMvc.perform(get("/api/persons"))
.andDo(print());
}
}
When I run this test I get
MockHttpServletResponse:
Status = 200
Error message = null
Headers = [Vary:"Origin", "Access-Control-Request-Method", "Access-Control-Request-Headers", X-Content-Type-Options:"nosniff", X-XSS-Protection:"0", Cache-Control:"no-cache, no-store, max-age=0, must-revalidate", Pragma:"no-cache", Expires:"0", X-Frame-Options:"DENY"]
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []
Even my status is 200, i have an empty body response, and I can't understand why
My controller:
@RestController
@RequestMapping("/api/persons")
public class PersonController {
private final PersonService service;
@Autowired
public PersonController(PersonService service) {
this.service = service;
}
@GetMapping
@Operation(
summary = "Returns a page of all persons "
)
public ResponseEntity<Page<PersonGetDTO>> getPersons(@PageableDefault(page = 0, size = 5, sort = "dateTime", direction = Sort.Direction.DESC) Pageable pageable,
@AuthenticationPrincipal User user) {
return service.getPersons(pageable, user);
}
My service:
public interface PersonService {
ResponseEntity<Page<PersonGetDTO>> getPersons(Pageable pageable, User user);
}
P.S. using postman all works and returns valid page of Persons, i guess the problem in using Mockito.when(), but i can't understand where is the mistake
I tried to use different mocks in thenReturn(), but it didn't help