Book with id:2 is not found – @InjectMocks is not working – SpringBoot

I am trying to test BookService class and in that class method findBookById()

  @RunWith(MockitoJUnitRunner.class)
    class BookServiceTest {
    
    @InjectMocks
    BookService bookService;
    
    @Mock
    BookRepository bookRepository;
    
    @Mock
    private ModelMapper modelMapper;
    private BookDto bookDto = new BookDto();
    private Book book = new Book();
    private Book book1 = new Book();
    private List<Book> books = new ArrayList<>();
    private List<BookDto> bookList = new ArrayList<>();
    
    @Test
    void findBookById() {
    book.setId(2L);
    book.setTitle("Harry Potter");
    book.setAuthor("J. K. Rowling");
    book.setPublisher("Bloomsbury Publishing");
    book.setCategory(Category.CLASSIC);
    book.setTotalCount(10);
    book.setRented(0);
    
    bookDto = bookService.findBookById(2L);
         Mockito.when(bookRepository.findById(2L)).thenReturn(java.util.Optional.ofNullable(book));
assertNotNull(bookDto);
assertEquals("Harry Potter", bookDto.getTitle());
assertEquals(book, bookService.findBookById(2L));
        }

From this code I am getting an error

com.example.library.exception.BookNotFoundException: Book with id:2 is not found.

UPDATE

When I try to do assertEquals(book, bookService.findBookById(2L));

I am getting following error:

org.opentest4j.AssertionFailedError: Expected :Book(id=2, title=Harry Potter, author=J. K. Rowling, publisher=Bloomsbury Publishing, category=CLASSIC, totalCount=10, rented=0) Actual :BookDto(id=2, title=Harry Potter, author=J. K. Rowling, publisher=Bloomsbury Publishing, category=CLASSIC, totalCount=10, rented=0)

Which I believe its coming from wrong injection of bookService. What am I missing here?

Answer

You first call bookService.findBookById(2L) and then stub bookRepository.findById(2L). Stubbing must go first, before calling method under test.

Mockito.when(bookRepository.findById(2L)).thenReturn(java.util.Optional.ofNullable(book));
var bookDto = bookService.findBookById(2L);
assertNotNull(bookDto);
assertEquals("Harry Potter", bookDto.getTitle());

Leave a Reply

Your email address will not be published. Required fields are marked *