Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito return value only when method is called for second time

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");
    }
  }
}

like image 686
Jon Avatar asked Apr 22 '26 13:04

Jon


1 Answers

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.

like image 156
Kaushik Avatar answered Apr 25 '26 03:04

Kaushik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!