How to verify that a specific method was not called using Mockito?
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??**
}
}
Hi, you can do this using the verify() method from the Mockito library. You can read more on the documentation here: https://static.javadoc.io/org.mockito/mockito-core/2.7.21/org/mockito/Mockito.html#never_verification. I've added a line of code to your example below.
public interface Dependency {
void someMethod();
}
public class Foo {
public bar(final Dependency d) { ... }
}
public class FooTest {
@Test
public void dependencyIsNotCalled() {
final Foo foo = new Foo(...);
final Dependency dependency = mock(Dependency.class);
foo.bar(dependency);
verify(dependency, never()).someMethod(); // verify it was called 0 times