In my simple example below, I am wondering how I can get nameManager to return a name only after nameManager.getName() is called for the second time with Mockito? (I know there are other things I can do, such as mocking what saveName() does)
I thought about using doAnswer(), but I don't know how to determine when nameManager.getName() has been called twice.
public void saveName(String name) {
boolean doesNameExist = nameManager.getName(name).isPresent();
if (!doesNameExist) {
saveName(name);
if (!nameManager.getName(name).isPresent()) {
throw new Exception("Cannot verify name has been saved");
}
}
}
In your unit test you can simply add the then clause twice. Like this -
@Test
public void yourUnitTest(){
when(nameManager.getName(anyString())
.thenReturn(null)
.thenReturn(someValue);
// your test
}
This will only return value when called second time and it will return null first time around.
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