简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM