Mockito 自调用 doAnswer 重复调用?
Mockito self-invoking doAnswer calls repeatedly?
我正在使用 mockito return 相同函数调用的不同值:
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 次),从而增加了这个计数器。不知道为什么会这样。这是正确的吗?
你的代码应该是正确的,除了你的语句中有一个警告,因为 Answer 是一个通用的 class。你应该写 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());
}
}
除了使用带有自制计数器的 Answer
,您还可以实现相同的行为链接 thenReturn
。
例如
when(thing.thingFunction()).thenReturn(object1).thenReturn(object2);
对于所有后续调用,将返回对象 2。
我正在使用 mockito return 相同函数调用的不同值:
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 次),从而增加了这个计数器。不知道为什么会这样。这是正确的吗?
你的代码应该是正确的,除了你的语句中有一个警告,因为 Answer 是一个通用的 class。你应该写 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());
}
}
除了使用带有自制计数器的 Answer
,您还可以实现相同的行为链接 thenReturn
。
例如
when(thing.thingFunction()).thenReturn(object1).thenReturn(object2);
对于所有后续调用,将返回对象 2。