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

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
1 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Neha Recent comment authors
newest oldest most voted
Neha
Guest
Neha

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