我试图使用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.....
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的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);
}
Run Code Online (Sandbox Code Playgroud)
fat*_*tih 29
您应该如下实例化testRef:
Test testRef = new Test(taskJob) {
public void updateAndReschedule(Long id, String message) {
//do nothing
}
};
Run Code Online (Sandbox Code Playgroud)
不需要间谍.