Verifying a method never invoked

In this post under Mockito I will show with example how to verify non-invocation of a method.

For our example we will use the below class

Class14

package package14;

public class Class14 {
    public void method1(boolean invoke) {
        if(invoke)
            display();
    }
    public void display() {
    }
}

In the above class, we have two methods “method1” and “display”. The method “method1” calls the other method “display” if and only if the “invoke” parameter is true or else skip the call.

We have to verify that when we pass “invoke” parameter as false, the “method1” should not call “display” method.

Below is the test class for that

Class14Test

package package14;

import static org.mockito.Mockito.*;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

@ExtendWith(MockitoExtension.class)
class Class14Test {
    @Mock
    private Class14 class14;

    @Test
    public void testMethod1() {
        class14.method1(false);

        verify(class14, never()).display();
    }
}

In the above code, at line 13, I create a mock of “Class14” which is the class to be tested.

In the method “testMethod1”. At line 17, I call “method1” passing false as the parameter.

As a result of passing false parameter to “method1”, the instance of “Class14” should not call “display” method.

To verify that, I have used Mockito’s “verify” method at line 19.

Using the Mockito’s “verify” method I am telling Mockito to verify “Class14” never calls “display” method.

In this way we can verify that a method is never called on an instance.

Leave a comment