【发布时间】:2022-10-23 13:45:41
【问题描述】:
我在 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")
.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 <{httpStatus=BAD_REQUEST, errorMessage=size parameter is missing, errorCode=400}>
当我删除 the line .andExpect(jsonPath("$", hasSize(2)))` 时,我得到 404 而不是 200。
【问题讨论】:
-
从您的端点返回的“大小参数丢失”应该很清楚,不是吗?
标签: java spring-boot junit