Mockito VerifyNoMoreInteractions and Unverified Interactions

25 Apr 2021

Junit’s verify and verifyNoMoreInteractions are great ways to ensure that the code is making the exact calls that you expect and with the exact parameters you expect.

  • In some cases, it is also simpler and more useful to add verifyNoMoreInteractions on the major dependencies in the after section of your code, so all of test method’s calls verify that they are not making extra calls that you do not expect.
class MyServiceTest(){

  @Mock
  private final MyDBConn myDbConnMock;

....

  @Test
  public void myTest(){
      myService.callFunction(xyz);
      verify(myDbConnMock).get(param1, param2)
  } 

  @After
  pubic void afterTest {
      verifyNoMoreInteractions(myDbConnMock);
  }
}
  1. In some cases, you might see there are more interactions that you expected, but also unverified interactions in the list below.
  2. This usually points to the same underlying issue where the call parameters are incorrect.
No interactions wanted here: -> at com.xyz.services.service....
found this interaction on mock 'mockDBConn': -> at ....

***
For your reference, here is the list of all invocations ([?] - means unverified).
1. -> at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
2. -> at com.xyz.myService.service...
3. [?]-> at com.xyz.myService.methodders.java:207)
4. -> at com.xyz.myservice.method2

? in the above code indicates the call wasn’t verified. This and the statement above indicate these are not two different issues, but instead they are both resulting from the right parameters not being checked for.

who am i

I am a data engineer with interests in databases, data science, algorithms and programming in general.

where am i

linkedin//rchamarthi
stackoverflow/users/237939/rchamarthi
Content available under Creative Commons (BY-NC-SA) unless otherwise noted.
This site is hosted at Github Pages and created with Jekyll. It uses the papyrus theme