mockito verify method call inside method

僤鯓⒐⒋嵵緔 提交于 2020-12-08 07:07:11

问题


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


回答1:


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



回答2:


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

And create MyVideoService with this mocked instance, call method, verify:

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


来源:https://stackoverflow.com/questions/36452240/mockito-verify-method-call-inside-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!