How to print all interactions with a mock using Mockito

USer22999299 :

So let's say I have to write some test on ClassA that has a ClassB as member and I'm mocking ClassB.

At the end of the test i would like to use verify(..) and verifyNoMoreInteractions(..) to set the behaviour and validation for all of the mock calls.

Let's say that the mock has more than 10 interactions with different methods.

Is there any way to get JUnit to print all of the mock interactions and then use it in the code?

Right now I'm just reading the code and looking for the calls and than writing the verification line in the test. I'm sure there is an easier way (TDD wont be possible in my situation :))

My use case: I have a class with an algorithm that uses a lot of other classes that I mock. While adding a new method that calls tons of other methods, I would like to make sure that only x amount of methods been called y amount of times as the code working now. This will make sure if someone changes something in the future, let's say by mistake calling a method 5 times instead of 4, then the test will fail.

Jeff Bowman :

You can use MockingDetails and either printInvocations or getInvocations to inspect the interactions belonging to a mock. However, this will not produce a list of invocations belonging to multiple mocks in the order that happened: just interactions with each individual mock.

Code snippet, as contributed by elhefe and Anand Rockzz:

import static org.mockito.Mockito.mockingDetails;

System.out.println(mockingDetails(mock).printInvocations());
/* or */
System.out.println(mockingDetails(mock).getInvocations());

Acknowledging your reluctance and caveats in the comments, I would say that this is a technique that does more to lock in your current implementation than to analyze your real constraints and prevent regressions. Furthermore, if your algorithm has a lot of interactions with direct collaborators, that might be an indication that the algorithm should be refactored.

If the system is untested or undocumented legacy code, this might be a practical way to programmatically generate a regression test or analysis--a temporary starting point for more-informed regression testing--but in your shoes I would instead start by documenting the contract of each component and then writing a test that confirms those interactions and constraints. Mockito recommendations (as intimated through this article by Mockito's original developer) tend toward adding stubs until tests pass and adding verifications/counts only where there are expensive or non-idempotent side effects.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=452895&siteId=1
Recommended