Skip to content

Instantly share code, notes, and snippets.

Embed
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
return;
}
}
}
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:",
wanted,
new LocationImpl(),
"Actual invocation has different arguments:",
actual,
actualLocation,
""
);
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()
.getSuspiciouslyNotMatchingArgsIndexes(wanted.getMatchers(),
invocation.getArguments());
final SmartPrinter smartPrinter = new SmartPrinter(wanted, invocation,
indicesOfSimilarMatchingArguments);
argumentsAreDifferent(smartPrinter.getWanted(), smartPrinter.getActual(),
invocation.getLocation());
}
}
import static com.pascalwelsch.mockito.LastCall.lastCall;
// usage
verify(view, lastCall()).showLoadingIndicator(false);
@passsy

This comment has been minimized.

Copy link
Owner Author

@passsy passsy commented Dec 15, 2016

Inspired by @jacek-marchwicki https://gist.github.com/jacek-marchwicki/006d4c5f61158cfef39a

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