单元测试我试图验证是否存在 一种使用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);
答案 0 :(得分:1)
让我们假设您有一个班级
class MyVideoService {
final VideoService videoService;
public MyVideoService(VideoService videoService) {
this.videoService = videoService;
}
public void delete(param) {
videoService.deleteVideo(param);
}
}
然后用
模拟VideoServiceVideoService videoService = mock(VideoService.class);
使用此模拟实例创建MyVideoService,调用方法,验证:
MyVideService myVideoService = new MyVideoService(videoService);
myVideoService.delete (param);
verify(videoService, times(1)).deleteVideo(param);
答案 1 :(得分:0)
你可以使用间谍。
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
的对象。 E.g。
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");
}
}