Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mockito verify method call inside method

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);

like image 689
Tvt Avatar asked Apr 06 '16 13:04

Tvt


1 Answers

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");
  }
}
like image 95
René Link Avatar answered Sep 29 '22 12:09

René Link