Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (3.4k points)

How to verify that a method is not called on an object's dependency?

For example:

public interface Dependency {

    void someMethod();

}

public class Foo {

    public bar(final Dependency d) {

        ...

    }

}

With the Foo test:

public class FooTest {

    @Test

    public void dependencyIsNotCalled() {

        final Foo foo = new Foo(...);

        final Dependency dependency = mock(Dependency.class);

        foo.bar(dependency);

        **// verify here that someMethod was not called??**

    }

}

2 Answers

0 votes
by (46k points)

The best way to verify that a specific method was not called using Mockito is to use the following syntax:

import static org.mockito.Mockito.never;

import static org.mockito.Mockito.verify;

// ...

verify(dependency, never()).someMethod();

For documentation of the feature used in the above syntax click here and for never click here.

0 votes
by (3.1k points)

To say that a certain method was not called in a test using Mockito, you would use verify with times(0). 
 
Example Code 
 
import static org.mockito.Mockito.*; 
import org.junit.jupiter.api.Test; 
 
public class MyServiceTest { 
 
@Test 
public void testMethodNotCalled() { 
MyService myService = mock(MyService.class); 
 
// Perform actions that should NOT call myService.someMethod() 
// Verify that someMethod() was not called 
verify(myService, times(0)).someMethod(); 
} 
} 
Explanation 
verify(myService, times(0)).someMethod(); checks that someMethod was never called on myService. 
If someMethod was called, this verification will fail the test, making sure the method has actually not been invoked. 

Related questions

1.2k questions

2.7k answers

501 comments

693 users

Browse Categories

...