我试图用mockito spy来模拟一个类的示例。我读了这篇博客文章,可能是为了测试所描述的行为是否真实,但它并没有达到我的预期。下面是一个简短的自包含(in)正确示例:
import org.mockito.Mockito;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.when;
public class Sandbox {
static class Foo {
// nothing
}
public static class Subject {
public int doStuffNoParameters() {
System.out.println("doStuffNoParameters called");
return -1;
}
public int doStuff(Foo f, String s) {
System.out.println("doStuff called!");
return 42;
}
}
public static void main(String[] args) {
Subject s = new Subject();
final Subject mock = Mockito.spy(s);
System.out.println((mock.doStuffNoParameters())); // expected doStuffNoParameters , -1
// mock method with no parameters using when or doReturn
doReturn(1).when(mock).doStuffNoParameters();
System.out.println(mock.doStuffNoParameters()); // expected 1
when(mock.doStuffNoParameters()).thenReturn(1);
System.out.println(mock.doStuffNoParameters()); // expected 1
// mock method with no parameters using when or doReturn
doReturn(1).when(mock).doStuff(Mockito.any(Foo.class), Mockito.anyString());
System.out.println(mock.doStuff(null, null)); // expected 1, got doStuff called then 42
when(mock.doStuff(Mockito.any(Foo.class), Mockito.any(String.class))).thenReturn(1); // expected nothing, got doStuffCalled
System.out.println(mock.doStuff(null, "anyway")); // expected 1; got doStuff called then 42
}
}
输出为:
doStuffNoParameters called
-1
1
1
doStuff called!
42
doStuff called!
doStuff called!
42
预期输出在代码中。特别是,我想知道,当函数调用的参数可能不可用、来自不同示例或在编写模拟行为时为null时,如何使用参数模拟对函数的调用。使用mockito v2.28.2编辑
1条答案
按热度按时间zhte4eai1#
调用时达到预期的行为
nullable(Clazz.class)
而不是any
正如dreamcrash的评论和这篇文章所强调的