我最近看到一些使用 Mockito 1.9.5 的代码,它的工作方式如下:
MyObject myObject = new MyObject();
...
Mockito.when(myObject.someMethod()).thenReturn("bogus");
由于myObject并不是一个模拟对象,而是一个非模拟类的实例,我惊讶地发现这段代码编译并运行没有导致单元测试失败。我本来以为会出现失败,提示“您要求我在非模拟对象上设置期望,并且我只期望在模拟对象上设置期望。”
为什么这段代码不会导致测试失败?
更新:添加更多的代码以实际复制我觉得困惑的行为。这些示例完全说明了我的问题。下面的代码表现出了我预期的行为--当我运行这个测试时,测试失败,信息为
when()需要一个参数,它必须是'模拟上的方法调用'。
public class AnotherObject{
public String doSomething(){
return "did something";
};
}
public class MyObject{
private AnotherObject anotherObject = new AnotherObject();
public void setAnotherObject(AnotherObject anotherObject) {
this.anotherObject = anotherObject;
}
public String someMethod(){
return anotherObject.doSomething();
}
}
@Test
public void WhyDoesWhenWorkOnNonMock() throws Exception {
MyObject myObject = new MyObject();
Mockito.when(myObject.someMethod()).thenReturn("bogus");
}
如果我给这个编造的测试添加一些具体的行,尽管我之前期望的是相同的失败和相同的消息,但现在测试不再失败了:
public class AnotherObject{
public String doSomething(){
return "did something";
};
}
public class MyObject{
private AnotherObject anotherObject = new AnotherObject();
public void setAnotherObject(AnotherObject anotherObject) {
this.anotherObject = anotherObject;
}
public String someMethod(){
return anotherObject.doSomething();
}
}
@Test
public void WhyDoesWhenWorkOnNonMock() throws Exception {
MyObject myObject = new MyObject();
AnotherObject mockAnotherObject = Mockito.mock(AnotherObject.class);
myObject.setAnotherObject(mockAnotherObject);
Mockito.when(myObject.someMethod()).thenReturn("bogus");
}