Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Mockito verification of the last call on a method
package com.pascalwelsch.mockito;
import org.mockito.exceptions.base.MockitoException;
import org.mockito.exceptions.verification.ArgumentsAreDifferent;
import org.mockito.internal.debugging.LocationImpl;
import org.mockito.internal.invocation.InvocationMatcher;
import org.mockito.internal.junit.JUnitTool;
import org.mockito.internal.reporting.SmartPrinter;
import org.mockito.internal.verification.api.VerificationData;
import org.mockito.internal.verification.argumentmatching.ArgumentMatchingTool;
import org.mockito.invocation.Invocation;
import org.mockito.invocation.Location;
import org.mockito.verification.VerificationMode;
import java.util.List;
import static org.mockito.internal.util.StringJoiner.join;
public class LastCall implements VerificationMode {
public static LastCall lastCall() {
return new LastCall();
public void verify(VerificationData data) {
List<Invocation> invocations = data.getAllInvocations();
InvocationMatcher matcher = data.getWanted();
for (int i = invocations.size() - 1; i >= 0; i--) {
final Invocation invocation = invocations.get(i);
if (invocation.getMethod().equals(matcher.getMethod())) {
if (!matcher.matches(invocation)) {
// throw
argumentsAreDifferent(matcher, invocation);
} else {
// match
throw new MockitoException("Not invoked at all");
private void argumentsAreDifferent(String wanted, String actual, Location actualLocation) {
final String message = join("Argument(s) for last call are different! Wanted:",
new LocationImpl(),
"Actual invocation has different arguments:",
if (JUnitTool.hasJUnit()) {
throw JUnitTool.createArgumentsAreDifferentException(message, wanted, actual);
} else {
throw new ArgumentsAreDifferent(message);
private void argumentsAreDifferent(InvocationMatcher wanted, Invocation invocation) {
final Integer[] indicesOfSimilarMatchingArguments =
new ArgumentMatchingTool()
final SmartPrinter smartPrinter = new SmartPrinter(wanted, invocation,
argumentsAreDifferent(smartPrinter.getWanted(), smartPrinter.getActual(),
import static com.pascalwelsch.mockito.LastCall.lastCall;
// usage
verify(view, lastCall()).showLoadingIndicator(false);

This comment has been minimized.

Copy link
Owner Author

@passsy passsy commented Dec 15, 2016

Inspired by @jacek-marchwicki

This solution check not only the last call on a the Object but the last call of the verifying method on the Object

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment