Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mock a CrudRepository findById ("111").get ()

I need to mock Spring crudRepository findById("111").get() from my test class

my code look like below and it return null even if I follow below steps.

(1) I need to test my Service class and I created serviceTest class and used mokito and powermock

(2) there is method ,i need to get User giving a id where service class method just calling to repository findById("111").get () and return the User object

(3) moking the test method like this

//configuration codes working well
.
.
.
tesst123 () {
.
.
//here some code working well
.
.
.
when (mockRepository.findById("111").get()).thenReturn (new User());

}

in above i can mock the mockRepository and while debugging it showed the created object.

But if I evaluate mockRepository.findById("111") part while debugging, it return null

if I evaluate mockRepository.findById("111").get() part while debugging, it return nullPointer exception

**** finally I sow .get() method return Optional.class and it is final class

So is there any way to mock this kind of scenarios ?

like image 679
sashikab Avatar asked Mar 20 '18 16:03

sashikab


1 Answers

Your method that you want to mock returns an Optional object. By default when you do not mock / stub Mockito returns the default values for the return type i.e null for object references (including Optional in your case) or applicable values for primitives e.g 0 for int.

In your scenario you are trying to mock the call to get() on the result of your dependent method i.e findById(). So according to rules of Mockito findById() still returns null because you did not stub it

What you need is this

tesst123 () {
   //some code as before
   User userToReturn = new User(); 
   when(mockRepository.findById("111")).thenReturn(Optional.of(userToReturn));
   //verifictions as before
 }
like image 105
ekem chitsiga Avatar answered Nov 13 '22 11:11

ekem chitsiga