Test a method which calls another method of the object in mockito

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:

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

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

So I don’t want to repeat all test cases for it in the test for 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.

.
.
.
.