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 ?
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With