Issue
I have an issue to write a RestControler Junit in Spring Boot. I have a problem in listBook in when option.
How can I fix the issue?
Here is the method of restController shown below.
@GetMapping("/search")
public ResponseEntity<List<BookResponse>> listBook(@RequestParam(name = "size") int size, @RequestParam(name = "page") int page) {
final Long userID = userService.findInContextUser().getId();
return ResponseEntity.ok(bookListService.listBooks(size, page, userID));
}
Here is the test method shown below
@Test
void itShouldGetBooks_WhenSearch() throws Exception {
// given - precondition or setup
BookResponse response1 = BookResponse.builder()
.title("Book 1")
.authorName("authorName")
.build();
BookResponse response2 = BookResponse.builder()
.title("Book 1")
.authorName("authorName2")
.build();
List<BookResponse> response = List.of(response1, response2);
UserDto userDto = UserDto.builder()
.id(1L)
.username("username")
.build();
// when - action or the behaviour that we are going test
when(userService.findInContextUser()).thenReturn(userDto);
when(bookListService.listBooks(anyInt(), anyInt(), eq(userDto.getId()))).thenReturn(response);
// then - verify the output
mockMvc.perform(get("/api/v1/book/search?size=" + anyInt() + "&page=" + anyInt()) // HERE IS THE ERROR LINE
.contentType(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(jsonPath("$", hasSize(2))) // ERROR IS HERE
.andExpect(status().isOk());
}
Here is the error message shown below.
java.lang.AssertionError: JSON path "$"
Expected: a collection with size <2>
but: was LinkedHashMap <{error=Request processing failed; nested exception is org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Invalid use of argument matchers!
0 matchers expected, 2 recorded:
Solution
Here is the solution shown below.
Change
mockMvc.perform(get("/api/v1/book/search?size=" + anyInt() + "&page=" + anyInt())
to
mockMvc.perform(get("/api/v1/book/search?size=" + 1 + "&page=" + 1)
Answered By - S.N
Answer Checked By - Robin (JavaFixing Admin)