如何验证一个非模拟对象被调用的方法?
2022-08-31 08:00:07
似乎 mockito 只验证是否调用了 mock 对象的方法,并且 mock 对象始终具有类似的东西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(...);
}