最佳答案
仿真程序似乎只验证是否调用了一个仿真对象的方法,而仿真对象总是具有类似于 doReturn().when(mock object)
的内容
但是我可以创建一个模拟对象并定义 doReturn().when(mock object)
吗
然后验证另一个对象的方法是否被调用?
下面是我想要做的: 我定义一个模拟环境,并且不管发生什么事情都返回一个响应。然后我想验证另一个 Obj 在不同情况下调用的不同方法。
怎么做?
public class BaseClass {
private Environment mockEnvironment;
@Test
public void testcase () {
setMockitoEnvironment();
response = foo(mockEnvironment, argument1);
verify(anotherObj).codePath1(...);
response = foo(mockEnvironment, argument2);
verify(anotherObj).codePath2(...);
}
}
//this method successfully return a response with any input
//because I do not care how response is eventually generated,
//I only care whether code path reaches createResponse() via
//code path 1 or code path 2.
private void setMockitoEnvironment() {
mockEnvironment = mock(Environment.class);
doReturn (response).when(mockEnvironment).createResponse(for any input);
}
private Response foo(...) {
...
return createResponse(...);
}