Mockito check method call inside method

for unit tests, I'm trying to check if there is a way to test a method call inside a method with mockito check?

Example:

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

I can check if deletion is called with:

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

Is there a way to check the internal method, for example: check (layout, times (1)) delete (pairs). VideoService.deleteVideo (pairs) ;.

+4
source share
2 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 want to test an object that uses MyVideoService. For instance.

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");
  }
}
0
source

Suppose you have a class

class MyVideoService {

 final VideoService videoService;

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

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

Then you mock VideoService with

VideoService videoService = mock(VideoService.class);

MyVideoService , , :

MyVideService myVideoService = new MyVideoService(videoService);
myVideoService.delete (param);
verify(videoService, times(1)).deleteVideo(param);
0

All Articles