简体   繁体   English

使用 Mockito 跳过方法执行

[英]Skipping a method execution using Mockito

I'm using Mockito for unit testing and I want to skip the execution of a method.我正在使用 Mockito 进行单元测试,我想跳过方法的执行。

I referred to this ticket Skip execution of a line using Mockito .我提到了这张票跳过使用 Mockito 的一行的执行 Here, I assume doSomeTask() and createLink() methods are in different classes.在这里,我假设 doSomeTask() 和 createLink() 方法在不同的类中。 But in my case, both the methods are in the same class (ActualClass.java).但就我而言,这两种方法都在同一个 class (ActualClass.java) 中。

//Actual Class

public class ActualClass{
    
    //The method being tested
    public void method(){
        //some business logic
        validate(param1, param2);

        //some business logic
    }

    public void validate(arg1, arg2){
        //do something
    }
}

//Test class

public class ActualClassTest{

    @InjectMocks
    private ActualClass actualClassMock;

    @Test
    public void test_method(){

        ActualClass actualClass = new ActualClass();
        ActualClass spyActualClass = Mockito.spy(actualClass);

        // validate method creates a null pointer exception, due to some real time data fetch from elastic

        doNothing().when(spyActualClass).validate(Mockito.any(), Mockito.any());
        actualClassMock.method();
    }
}

Since there arises a null pointer exception when the validate method is executed, I'm trying to skip the method call by spying the ActualClass object as stated in the ticket I mentioned above.由于在执行 validate 方法时出现 null 指针异常,我试图通过监视 ActualClass object 来跳过方法调用,如我上面提到的票证中所述。 Still, the issue is not resolve.尽管如此,问题仍未解决。 The validate method gets executed and creates a null pointer exception due to which the actual test method cannot be covered. validate 方法被执行并创建一个 null 指针异常,因此无法覆盖实际的测试方法。

So, how do I skip the execution of the validate() method that is within the same class.那么,如何跳过同一个 class 中的 validate() 方法的执行。

In case of any external dependencies the following two annotations can be used at once.如果有任何外部依赖项,可以同时使用以下两个注释。 @InjectMocks @Spy This will actually spy the original method. @InjectMocks @Spy 这实际上会监视原始方法。 If the method you want to skip exists in some other file, annotate the object of the class with @Spy in which the method to be skipped exists.如果你要跳过的方法存在于其他文件中,将class中的object注解为@Spy,其中存在要跳过的方法。

You must always use your spy class when calling method() .调用method()时,您必须始终使用间谍 class。

   @Test
    public void test_method(){
        ActualClass spyActualClass = Mockito.spy(actualClassMock);

        doNothing().when(spyActualClass).validate(Mockito.any(), Mockito.any());
        spyActualClass.method();
    }

In practice, instead of在实践中,而不是

actualClassMock.method();

you must use你必须使用

spyActualClass.method();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM