Search code examples
springjunitmockito

Wrong value JUnit5/Mockito


I'm new on module testing. Please, help me to find, what I'm doing wrong.

My repository:

@Repository
public interface BookRepository extends JpaRepository<Book, Integer> {
    List<Book> findByAuthorContainingIgnoreCase(String author);
    List<Book> findByGenreContainingIgnoreCase(String genre);
    List<Book> findByNameContainingIgnoreCase(String name);
}

My Service:

public List<Book> findByAuthorContaining(String author){
        return bookRepository.findByAuthorContainingIgnoreCase(author);
}

And Tests:

    @Test
    public void findByAuthors(){
        List<Book> books = getBooks();
        Mockito.when(bookRepository.findByAuthorContainingIgnoreCase(any())).thenReturn(books);

        List<Book> result = bookService.findByAuthorContaining("testAuthor2");

        Assertions.assertEquals(1, result.size());
    }

    private List<Book> getBooks(){
        Book firstBook = new Book();
        Book secondBook = new Book();

        firstBook.setId_book(1);
        firstBook.setAmount(1);
        firstBook.setImage("/test1");
        firstBook.setGenre("testGenre");
        firstBook.setAuthor("testAuthor");
        firstBook.setYear(2001);
        firstBook.setPages(1);
        firstBook.setPrice(1);

        secondBook.setId_book(2);
        secondBook.setAmount(2);
        secondBook.setImage("/test2");
        secondBook.setGenre("testGenre2");
        secondBook.setAuthor("testAuthor2");
        secondBook.setYear(2002);
        secondBook.setPages(2);
        secondBook.setPrice(2);

        return List.of(firstBook, secondBook);
}

My Method findByAuthorContaining works correctly. But when I running my module test, method returns all List (2 values), regardless the value I call. What should I do to fix that?


Solution

  • As Sledgehammer also mentioned in the comments, right now you are overriding the actual Spring Data JPA query and telling your mocked repository to always return back 2 books regardless (no actual query is ran against the db).

    If you are trying to test that the actual query works you will need to let the repository query fetch data from an actual db (in your case MySQL but you could also use H2). With that you can get rid of the mocked repository and query your database as an integration test.

    There should be plenty of examples of testing Spring Data JPA queries in integration tests.