gpt4 book ai didi

java - Mockito自调用doAnswer重复调用?

转载 作者:行者123 更新时间:2023-12-02 11:01:52 29 4
gpt4 key购买 nike

我使用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 次),从而增加该计数器。不知道为什么会发生这种情况。这是正确的吗?

最佳答案

除了语句中存在警告之外,您的代码应该是正确的,因为 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());
}
}

关于java - Mockito自调用doAnswer重复调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51273197/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com