Search code examples
javaspring-bootjunitmockito

Spring Boot JUnit Mockito Specification giving null object


I have a problem about writing a Junit with Mockito for Specification in Spring Boot.

I get null result of the bookListResponseResult after defining a bookRepository within when.

How can I fix it?

Here is the method inside the service.

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

Here is the response shown below.

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

Here is the JUnit test method shown below.

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

    }

Here is the result shown below of bookListResponseResult.

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

Solution

  • After I revised the code shown below, the issue disappeared.

    Change

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

    To

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