提供空对象的Spring Boot JUnit Mockito规范

2ledvvac  于 2022-11-08  发布在  Spring
关注(0)|答案(1)|浏览(134)

我在用Mockito为Spring Boot中的规范编写Junit时遇到了一个问题。
在when内定义bookRepository后,我得到了bookListResponseResult的空结果。
我该如何修复它?
下面是服务内部的方法。

public List<BookResponse> searchByTitle(String title) {
       return bookRepository.findAll(BookSearchSpecification.search(title))
               .stream()
               .map(BookListService::response)
               .collect(Collectors.toList());
    }

以下是响应。

private static Response response(Book book) {
   return Response.builder().title(book.getTitle())
                .build();
}

下面是JUnit测试方法。

@Test
    void searchByTitle() {

        // given - precondition or setup
        Response response1 = Response.builder()
                .title("Book Title")
                .build();

        Response bookResponse2 = Response.builder()
                .title("Book Title")
                .build();

        List<BookResponse> bookListResponse = Arrays.asList(bookResponse1,bookResponse2);

        Category category = Category.builder().name("Category 1").build();

        Request saveBookRequest1 = Request.builder()
                .title("Book Title")
                .build();

        Request saveBookRequest2 = Request.builder()
                .title("Book Title")
                .build();

        Book book1 = Book.builder().category(category)
                .title(saveBookRequest1.getTitle())
                .build();

        Book book2 = Book.builder().category(category)
                .title(saveBookRequest2.getTitle())
                .build();

        when(
                bookRepository.findAll(any(Specification.class))
        ).thenReturn(Arrays.asList(book1,book2));

        List<Response> bookListResponseResult = bookListService.searchByTitle("Book Title"); // return null 
        assertEquals(bookListResponse.get(0).getTitle(), bookListResponseResult.get(0).getTitle());
        assertEquals(bookListResponse.get(1).getTitle(), bookListResponseResult.get(1).getTitle());

    }

下面显示的是bookListResponseResult的结果。

Response(id=null, title=null)
Response(id=null, title=null)
i2byvkas

i2byvkas1#

在我修改了下面所示的代码之后,这个问题就消失了。
变更

List<BookResponse> bookListResponse = Arrays.asList(bookResponse1,bookResponse2);

结束日期

List<Response> bookListResponse = Arrays.asList(bookResponse1,bookResponse2);

相关问题