This is another chapter of our little story through the ApexMocks counters for the inOrder verification.
You have probably already encountered the first chapter about the inOrder verification.
You have probably noticed that those verifications were some how incomplete in their functionality, but not anymore.
The times() added the possibility to verify the exact number of calls, and then the atLeast() get along. The atLeast() and calls() both set the minimum number of calls that are expected for that method, but they behave differently. The atLeast() is greedy, instead the calls() is not.
Greedy? Not greedy? What does it mean?
To explain the greedy concept we first need to talk about the invocation consumed.
The inOrder stores the invocations methods called on the mocked instance sequentially, in a list. Then when we verify the inOrder goes through this list and “consume” those invocations.
The atLeast(), being greedy, would consume all the invocations that match the method under verification instead, the calls() would consume only those that have been verified.
Let’s see with some pseudo code.
1 softDev.writeSomeCode(); 2 softDev.writeSomeCode(); 3 softDev.drinkCoffe(); 4 softDev.writeSomeCode(); 5 softDev.blameSlowNetwork(); 6 softDev.writeSomeCode(); 7 softDev.writeSomeCode(); 8 softDev.gitCommit();
performing the following verify
((ISoftwareDeveloper) inOrder.verify( mockProductiveDeveloper, MY_MOCKS.calls(2))).writeSomeCode();
the next available invocation to be verified in this case would be the drinkCoffe() at line 3.
Using the atLeast() instead
((ISoftwareDeveloper) inOrder.verify( mockProductiveDeveloper, MY_MOCKS.atLeast(2))).writeSomeCode();
since it consumes all the invocations that match our method, the next method that is available to be verified is gitCommit() at line 8.
A special version of the atLeast() is also available: atLeastOnce(). Guess how many time is expected to be called…
The adding of atLeast() counter for the inOrder verification it narrows down the gap of funcionality between ApexMocks and Mockito, giving more flexibility to your mock verification.