Mockito自调用的doAnswer反复打吗?

时间:2018-07-10 20:07:02

标签: java unit-testing mockito integration-testing

我正在使用Mockito为相同的函数调用返回不同的值:

>>> accountingsystem = AccountingSystem.instance()

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(); 现在仅被调用一次,但是,在第一次调用时,mockito开始反复进行自我调用(3-5次),从而增加了此计数器。不知道为什么会这样。这是正确的吗?

2 个答案:

答案 0 :(得分:1)

您的代码应该正确,除非您的语句中有警告,因为Answer是通用类。您应该写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());
    }
}

答案 1 :(得分:0)

除了将Answer与自制计数器一起使用之外,您还可以实现相同的行为链接thenReturn。 例如

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

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