Home > Software engineering >  Skipping a method execution using Mockito
Skipping a method execution using Mockito

Time:03-05

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.

CodePudding user response:

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();
  • Related