RestController Junit在Spring Boot中出现问题时



我在Spring Boot中编写RestControler Junit时遇到问题。我在"何时"选项中的listBook中有问题。

如何解决此问题?

下面是restController的方法。

@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));
}

以下是显示的测试方法

@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());
}

下面显示了错误消息。

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:

您的方法被称为listBook,但您是在嘲笑listBooks(注意s(。listBook是用2个参数(int,int(定义的,但mock是用3个匹配器(int,整型,id(设置的。此外,不能将匹配符与文字值混合使用。要么所有参数都匹配,要么没有匹配(即所有参数都是实值(。

//                             vvvvvv----vvvvvv-- any matchers
when(bookListService.listBooks(anyInt(), anyInt(), eq(userDto.getId())))
//                                                 ^^-- equality matcher
.thenReturn(response);

以下是解决方案。

更改

mockMvc.perform(get("/api/v1/book/search?size=" + anyInt() + "&page=" + anyInt())

mockMvc.perform(get("/api/v1/book/search?size=" + 1 + "&page=" + 1)

最新更新