Check a method that calls another object method in mockito

I have an interface, for example:

interface MyService { void createObj(int id) void createObjects() } 

I want to check the implementation of the createObjects method, which has a body like:

 void createObjects() { ... for (...) { createObj(someId); } } 

I already tested 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)); } 

Therefore, I do not want to repeat all the test cases for the test in createObjects .

How can I make sure that another method of the real object was called in addition to the one I am testing?

+4
source share
1 answer

Use 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 .

+7
source

Source: https://habr.com/ru/post/1479364/


All Articles