How to print all layout interactions using Mockito

So, let's say I need to write a ClassA test that has a ClassB member, and I'm mocking ClassB .

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

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

Is there a way to get JUnit to print all layout interactions and then use it in code?

Now I am just reading the code and looking for calls, and not writing the verification string in the test. I am sure there is an easier way (TDD will not be possible in my situation :))

My use case: I have a class with an algorithm that uses many other classes that I mock up. Adding a new method that calls many other methods, I would like to make sure that only x the number of methods has been called several times as the code works. This will make sure that someone will change something in the future, for example, by mistake, calling the method 5 times instead of 4, then the test will fail.

+5
source share
1 answer

You can use MockingDetails and printInvocations or getInvocations to check for interactions belonging to the layout. However, this will not result in a list of calls belonging to several layouts, in the order in which this happened: just interacting with each individual layout.

Recognizing your reluctance and reservations in the comments, I would say that this is a method that does more to block your current implementation than to analyze your real limitations and prevent regressions. In addition, if your algorithm has many interactions with direct employees, this may be a sign that the algorithm should be reorganized.

If the system is untested or undocumented legacy code, this can 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 which confirms these interactions and limitations. Mockito recommendations (as shown by the original Mockito developer in this article ) tend to add stubs until tests pass and add checks / counts only where there are costly or non-idempotent side effects.

+10
source

Source: https://habr.com/ru/post/1260266/


All Articles