[英]Test a method which calls another method of the object in mockito
I have an interface, ex: 我有一个界面,例如:
interface MyService {
void createObj(int id)
void createObjects()
}
I want to test an implementation of the createObjects
method, which has body like: 我想测试createObjects
方法的实现,它具有如下体:
void createObjects() {
...
for (...) {
createObj(someId);
}
}
I have already tested createObj(id)
: 我已经测试了createObj(id)
:
@Test public void testCreate() {
//given
int id = 123;
DAO mock = mock(DAO.class);
MyService service = new MyServiceImpl(mock);
//when
service.createObj(id);
//verify
verify(mock).create(eq(id));
}
So I don't want to repeat all test cases for it in the test for createObjects
. 所以我不想在createObjects
的测试中重复它的所有测试用例。
How can I make sure that another method of the real object was called besides the one I am testing? 除了我正在测试的那个之外,我怎样才能确保调用真实对象的另一个方法?
Use a spy: 使用间谍:
MyService myService = new MyServiceImpl()
MyService spy = spy(myService);
doNothing().when(spy).createObj(anyInt());
// now call spy.createObjects() and verify that spy.createObj() has been called
This is described, like everything else, in the api doc . 这与api doc中的所有其他内容一样被描述。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.