在与被测试类(CUT)相同的类中使用Mockito到Stub方法

Sud*_*hir 25 java mockito

我试图使用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)

不需要间谍.

  • 您的方法不起作用,因为类Test不公开此方法.一个hack方法就是这样做:final boolean [] methodCalled = new boolean [1]; 测试testRef = new Test(taskJob){public void updateAndReschedule(Long id,String message){methodCalled [0] = true; }}; /*doStuff...*/ assertTrue(methodCalled [0]); (2认同)