gpt4 book ai didi

java - Mockito:在 void 方法上填充不同的值

转载 作者:行者123 更新时间:2023-11-30 05:52:28 25 4
gpt4 key购买 nike

我正在使用 Mockito 进行单元测试。我需要模拟一个填充一些输入的 void 方法。非常非常幼稚的例子:

class Something {
AnotherThing thing = new AnotherThing();
public int doSomething(Stuff stuff)
{
thing.doThing(stuff);
if(thing.getName().equals("yes")){
return 1;
}
else {
return 2;
}
}
}

class AnotherThing() {
public void doThing(Stuff stuff){
if(stuff.getName().equals("Tom")) {
stuff.setName("yes");
}
else {
stuff.setName("no");
}
}
}

class Stuff()
{
String name;
// name getters and setters here
}

在这种情况下,我将尝试模拟 AnotherThing 来测试 Something

但是,我在我正在测试的类中多次调用了这个 void 方法。每次调用它时,我都需要不同的“Answer”。我的意思是,我想在每次调用 void 方法时调用它来做不同的事情。

我查看了 API,但找不到解决方案。这甚至可以用 Mockito 实现吗?

最佳答案

您需要的是 Mockito Answer 对象。这是一个包含少量功能的对象,您可以在调用模拟方法时运行这些功能。查看 doAnswer 的 Mockito 文档了解更多详情;但基本上你想要的是这样的。

  doAnswer(new Answer<Object>(){
@Override
public Object answer(InvocationOnMock invocation){
Object[] arguments = invocation.getArguments();
Stuff argument = (Stuff) arguments[0];
if(stuff.getName().equals("Tom")) {
stuff.setName("yes");
}
else {
stuff.setName("no");
}
return null;
}
}).when(mockObject).doThing(any(Stuff.class));

关于java - Mockito:在 void 方法上填充不同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11624588/

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