有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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);

}

共 (2) 个答案

  1. # 2 楼答案

    您应该按如下方式实例化testRef:

    Test testRef = new Test(taskJob) {
    
        public void updateAndReschedule(Long id, String message) {
            //do nothing
        }
    
    };
    

    不需要间谍