我知道我不应该以这种方式使用 Mockito,但我不明白为什么这个 Mockito 代码:
public class Demo {
public static void main(String... args){
Foo foo = Mockito.mock(Foo.class);
Mockito.doReturn(-1).when(foo);
System.out.println(foo.myMethod("a"));
System.out.println(foo.myMethod("a"));
}
public interface Foo{
int myMethod(Object o);
}
}
给出这个结果:
0
-1
而不是:
0
0
最佳答案
doReturn()
缺少参数类型安全性。
来自 Mockito.doReturn()
javadoc (强调不是我的):
Use
doReturn()
in those rare occasions when you cannot usewhen(Object)
.Beware that Mockito.when(Object) is always recommended for stubbing because it is argument type-safe and more readable (especially when stubbing consecutive calls).
你实际上并没有像你必须的那样使用 when()
,所以你会得到一个奇怪的结果,因为它是宽容的。
您想要 stub Mock 的返回值:
Mockito.doReturn(-1).when(foo).myMethod(Mockito.any());
你不想 stub 模拟本身:
Mockito.doReturn(-1).when(foo);
这毫无意义:为什么引用 foo
应该返回一些东西?
或者更好地使用 Mockito.when()
,它不那么宽松:
Mockito.when(foo).thenReturn(-1); // same oddity will not compile
Mockito.when(foo.myMethod(any())).thenReturn(-1); // but it will compile
关于java - Mockito Stub 意外行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52117809/