对于单元测试,我试图验证是否存在
一种使用mockito验证方法内部方法调用的方法?
一个例子是:
public delete(param) {
VideoService.deleteVideo(param); << i want to verify the call of this method
return etc..
}
我可以检查是否调用删除:
verify(mock,times(1)).delete(param);
还有像检查内部方法的方法,如:
验证(模拟,倍(1))删除(PARAM).VideoService.deleteVideo(PARAM).
最佳答案 你可以使用间谍.
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) {
}
}
如果您现在要测试使用MyVideoService的对象.例如.
public class ObjectThatUsesMyVideoService {
private MyVideoService myVideoService;
ObjectThatUsesMyVideoService(MyVideoService myVideoService) {
this.myVideoService = myVideoService;
}
public void deleteVideo(String param) {
myVideoService.delete(param);
}
}
你可以写这样的测试
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");
}
}