mockito verify method call inside method

Tvt picture Tvt · Apr 6, 2016 · Viewed 11.4k times · Source

for a unit tests i am trying to verify if there is a way to verify a method call inside a method with mockito verify?

An example would be:

public delete(param) {
    VideoService.deleteVideo(param); << i want to verify the call of this method
    return etc.. 
}

I can check if delete is called with :

verify(mock,times(1)).delete(param);

Is there also like a way to check the inside method like: verify(mock,times(1)).delete(param).VideoService.deleteVideo(param);

Answer

Ren&#233; Link picture René Link · Apr 6, 2016

You can use a spy.

public class MyVideoService {

  private VideoService videoService;

  public MyVideoService(VideoService videoService) {
    this.videoService = videoService;
  }

  public void delete(String param) {
    videoService.deleteVideo(param);
  }
}

public class VideoService {
  public void deleteVideo(String param) {
  }
}

If you now want to test an object that uses MyVideoService. E.g.

public class ObjectThatUsesMyVideoService {

  private MyVideoService myVideoService;

  ObjectThatUsesMyVideoService(MyVideoService myVideoService) {
    this.myVideoService = myVideoService;
  }

  public void deleteVideo(String param) {
    myVideoService.delete(param);
  }
}

You can write a test like this

public class MyVideoServiceTest {

  @Test
  public void delete(){
    // VideoService is just a mock
    VideoService videoServiceMock = Mockito.mock(VideoService.class); 

    // Creating the real MyVideoService
    MyVideoService myVideoService = new MyVideoService(videoServiceMock);

    // Creating a spy proxy
    MyVideoService myVideoServiceSpy = Mockito.spy(myVideoService);

    ObjectThatUsesMyVideoService underTest = new ObjectThatUsesMyVideoService(myVideoServiceSpy);

    underTest .deleteVideo("SomeValue");

    // Verify that myVideoService was invoked
    Mockito.verify(myVideoServiceSpy, Mockito.times(1)).delete("SomeValue");

    // Verify that myVideoService invoked the VideoService
    Mockito.verify(videoServiceMock, Mockito.times(1)).deleteVideo("SomeValue");
  }
}