4

I’m using Mockito for unit testing and I want to skip the execution of a method.

I referred to this ticket Skip execution of a line using Mockito. Here, I assume doSomeTask() and createLink() methods are in different classes. But in my case, both the methods are in the same 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. 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.

So, how do I skip the execution of the validate() method that is within the same class.

2 Answers2

2

You must always use your spy class when calling method().

   @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();
pringi
  • 3,987
  • 5
  • 35
  • 45
2

In case of any external dependencies the following two annotations can be used at once. @InjectMocks @Spy This will actually spy the original method. 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.

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Mar 07 '22 at 20:45