Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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??**     } } 
like image 566
beluchin Avatar asked Oct 12 '12 15:10

beluchin


People also ask

Which method in Mockito verifies that no interaction has happened with a mock in Java?

Mockito verifyZeroInteractions() method It verifies that no interaction has occurred on the given mocks. It also detects the invocations that have occurred before the test method, for example, in setup(), @Before method or the constructor.

Does Mockito verify use equals?

Internally Mockito uses Point class's equals() method to compare object that has been passed to the method as an argument with object configured as expected in verify() method. If equals() is not overridden then java. lang.

How does verify Mockito?

Verify in Mockito simply means that you want to check if a certain method of a mock object has been called by specific number of times. When doing verification that a method was called exactly once, then we use: verify(mockObject).


2 Answers

Even more meaningful :

import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify;  // ...  verify(dependency, never()).someMethod(); 

The documentation of this feature is there §4 "Verifying exact number of invocations / at least x / never", and the never javadoc is here.

like image 68
Brice Avatar answered Sep 19 '22 05:09

Brice


Use the second argument on the Mockito.verify method, as in:

Mockito.verify(dependency, Mockito.times(0)).someMethod() 
like image 25
beluchin Avatar answered Sep 20 '22 05:09

beluchin