Mockito – How to mock repository findById thenReturn() Optional?

Try to mock a repository findById method, but no idea use thenReturn() to return an object, as it accepts an Optional?

P.S Tested in Spring Boot 2 environment


import static org.mockito.Mockito.*;
import org.springframework.boot.test.mock.mockito.MockBean;

	@MockBean
	private BookRepository mockRepository;
	
	@Before
    public void init() {
       
        Book book = new Book(1L, "A Book");
		
		//error, can't resolve method thenReturn(book)?
		when(mockRepository.findById(1L)).thenReturn(book); 

    }

Solution

Try Optional.of()


	@MockBean
	private BookRepository mockRepository;
	
	 @Before
    public void init() {
       
        Book book = new Book(1L, "A Book");
		when(mockRepository.findById(1L)).thenReturn(Optional.of(book));

    }

References

12 comments on “Mockito – How to mock repository findById thenReturn() Optional?

  1. Thank you so much I have been struggling for an hour .it solved my problem

    Reply
  2. Still getting NullPointerException
    new solution please???????????????

    Reply
  3. i want to write mockito which returns list. How to pass list object in Optional.of (). Could you help me on this.

    Reply
  4. Thanks a lot! Been looking for such a solution for a long time.

    Reply
  5. After passing it as Optional.of(T), when they are checking for T.isPresent() returns false. how to fix that?

    Reply
  6. Could you please guide us how to configure MongoDB embedded DB with the mickito and write controller based test classes?

    Reply

Leave a Comment

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