java使用Mockito将方法存根在与被测类相同的类中(CUT)
我正在尝试使用Mockito测试一些遗留代码,该方法的类型为void
我已经在其他类中删除了很多对方法的调用,这很好。 但是,我还需要能够在同一个类中删除对其他方法的某些调用
目前这不起作用
我的班级如下:
public class Test {
public Test(dummy dummy) {
}
public void checkTask(Task task, List <String> dependencyOnLastSuccessList) throws TaskException {
callToOtherClass.method1 // This works fine, I can stub it using mockito
updateAndReschedule(Long id, String message) // call to method in same class, I cannot stub it
}
public void updateAndReschedule(Long id, String message) {
//method logic.....
}
}
这是我的testClass,显示了我目前拥有的:
@Test
public void testMyMethod() {
Test testRef = new Test(taskJob);
Test spy = spy (testRef);
// when a particular method is called, return a specific object
when(callToOtherClass.method1).thenReturn(ObjectABC);
//doNothing when my local method is called
doNothing().when(spy).updateAndReschedule(1, "test");
//make method call
spy.checkTask(ts, taskDependencies);
}
# 1 楼答案
在我看来,间谍的目标不是嘲笑。 Spy是作为现有真实对象的代理创建的模拟;有些方法可以存根,而未存根的方法则转发给覆盖对象
间谍比所选方法的匿名实现更优雅
看看这个例子:
Mockito: Trying to spy on method is calling the original method
你可以读到关于mockito的好文章
http://refcardz.dzone.com/refcardz/mockito
# 2 楼答案
您应该按如下方式实例化testRef:
不需要间谍