【问题标题】:RestController Junit when issue in Spring Boot在 Spring Boot 中出现问题时的 RestController Junit
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

  • 我编辑了我的帖子。
  • @S.N 现在这是一个不同的问题(和一个不同的错误)。原来的问题解决了。新问题应该是:“如何使用 mockmvc 和 jsonpath 断言对象以包含特定数量的属性”。或者“如何通过 mockmvc 传递参数?”
猜你喜欢
  • 1970-01-01
  • 2019-05-11
  • 1970-01-01
  • 1970-01-01
  • 2023-03-10
  • 2019-05-14
  • 1970-01-01
  • 2020-09-27
  • 2019-08-03
相关资源
最近更新 更多