Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 395
glaz666 Avatar asked Mar 24 '23 01:03

glaz666


1 Answers

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.

like image 66
JB Nizet Avatar answered Mar 30 '23 00:03

JB Nizet