Sla*_*ice 4 java unit-testing mockito
我正在使用 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
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,我会尝试模拟AnotherThing来测试Something.
但是,我在我正在测试的类中多次调用此 void 方法。Answer每次调用它时我都需要不同的“ ”。我的意思是,我想在每次调用时调用 void 方法来做不同的事情。
我查看了 API,但找不到解决方案。Mockito 甚至可以做到这一点吗?
你需要的是一个 MockitoAnswer对象。这是一个包含一些功能的对象,您可以在调用模拟方法时运行这些功能。查看 Mockito 文档doAnswer了解更多详情;但基本上你想要的是这样的。
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));
Run Code Online (Sandbox Code Playgroud)