Main Tutorials

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 Author

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

Comments

Subscribe
Notify of
12 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Mithun
4 years ago

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

Patricio Di Muzio
3 years ago

Nup, im getting: java.lang.NullPointerException

Ti Bs
2 years ago

Still getting NullPointerException
new solution please???????????????

Daniela
2 years ago
Reply to  Ti Bs

I am in the same case, have you resolved this?

Debargha Roy
4 years ago

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

Bindu
2 years ago

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

Carla
2 years ago

Very helpful. Thanks.

Madhuwantha Bandara
3 years ago

Thank you vary much.It is very helpfull

balan
3 years ago

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

Janmejay
3 years ago
Reply to  balan

I am struggling with same scenario. Any solutions ?

sagar
4 years ago

Nice One

Neha
5 years ago

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