代码之家  ›  专栏  ›  技术社区  ›  John Lippson

Mockito自动调用DoAnswer是否重复调用?

  •  0
  • John Lippson  · 技术社区  · 6 年前

    我使用mockito为相同的函数调用返回不同的值:

    doAnswer(new Answer() {
      int counter = 0;
    
      @Override
      public Object answer(InvocationOnMock invocation) throws Throwable {
        if (counter == 0) {
            counter += 1;
          return object1;
        } else {
          return object2;
        }
      }
    }).when(thing).thingFunction();
    

    thingFunction 现在只调用一次,但是,在第一次调用时,mockito开始反复地自我调用(3-5次),从而增加了这个计数器。不知道为什么会这样。这是正确的吗?

    2 回复  |  直到 6 年前
        1
  •  1
  •   Ph1llip2    6 年前

    您的代码应该是正确的,除非您的语句中有警告,因为答案是一个泛型类。你应该写 new Answer<Object>() { //.. } (根据模拟方法的返回类型)

    我用Mockito 1.10.19写了一个JUnit测试来澄清:

    import org.mockito.Mockito;
    import org.mockito.invocation.InvocationOnMock;
    import org.mockito.stubbing.Answer;
    
    import static org.junit.Assert.*;
    
    import org.junit.Test;
    
    public class TestClass {
    
    
        Object object1 = new Object();
        Object object2 = new Object();
    
        class Thing{
            public Object thingFunction(){
                return null;
            }
        }
    
        @Test
        public void test(){
            Thing thing = Mockito.mock(Thing.class);
            Mockito.doAnswer(new Answer<Object>() {
                  int counter = 0;
    
                  @Override
                  public Object answer(InvocationOnMock invocation) throws Throwable {
                    if (counter == 0) {
                        counter += 1;
                      return object1;
                    } else {
                      return object2;
                    }
                  }
                }).when(thing).thingFunction();
    
            assertEquals(object1, thing.thingFunction());
            assertEquals(object2, thing.thingFunction());
        }
    }
    
        2
  •  0
  •   brass monkey    6 年前

    而不是使用 Answer 使用自制计数器,您还可以实现相同的行为链接。 thenReturn . 例如。

    when(thing.thingFunction()).thenReturn(object1).thenReturn(object2);
    

    对于所有后续调用,将返回object2。