Skip to content

Instantly share code, notes, and snippets.

@passsy
Forked from sockeqwe/LastCall.java
Last active February 13, 2017 14:35
Show Gist options
  • Save passsy/5c16f3a5a48574eb62a563633f8c8b13 to your computer and use it in GitHub Desktop.
Save passsy/5c16f3a5a48574eb62a563633f8c8b13 to your computer and use it in GitHub Desktop.
Mockito verification of the last call on a method (targeting org.mockito:mockito-core:2.7.5)
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.junit.JUnitTool;
import org.mockito.internal.reporting.SmartPrinter;
import org.mockito.internal.verification.VerificationModeFactory;
import org.mockito.internal.verification.api.VerificationData;
import org.mockito.internal.verification.argumentmatching.ArgumentMatchingTool;
import org.mockito.invocation.Invocation;
import org.mockito.invocation.MatchableInvocation;
import org.mockito.verification.VerificationMode;
import java.util.List;
import static org.mockito.internal.util.StringUtil.join;
public class LastCall implements VerificationMode {
public static LastCall lastCall() {
return new LastCall();
}
@Override
public VerificationMode description(final String description) {
return VerificationModeFactory.description(this, description);
}
public void verify(VerificationData data) {
List<Invocation> invocations = data.getAllInvocations();
final MatchableInvocation target = data.getTarget();
for (int i = invocations.size() - 1; i >= 0; i--) {
final Invocation invocation = invocations.get(i);
if (invocation.getMethod().equals(target.getInvocation().getMethod())) {
if (target.matches(invocation)) {
// matches, everything is fine
return;
} else {
throwArgumentsAreDifferentException(target, invocation);
}
}
}
throw new MockitoException("Not invoked at all");
}
private void throwArgumentsAreDifferentException(MatchableInvocation wanted,
Invocation invocation) {
final Integer[] indicesOfSimilarMatchingArguments =
ArgumentMatchingTool.getSuspiciouslyNotMatchingArgsIndexes(wanted.getMatchers(),
invocation.getArguments());
final SmartPrinter smartPrinter =
new SmartPrinter(wanted, invocation, indicesOfSimilarMatchingArguments);
final String message = join("Argument(s) for last call are different! Wanted:",
smartPrinter.getWanted(),
new LocationImpl(),
"Actual invocation has different arguments:",
smartPrinter.getActual(),
invocation.getLocation(),
""
);
if (JUnitTool.hasJUnit()) {
throw JUnitTool.createArgumentsAreDifferentException(message, smartPrinter.getWanted(),
smartPrinter.getActual());
} else {
throw new ArgumentsAreDifferent(message);
}
}
}
import static com.pascalwelsch.mockito.LastCall.lastCall;
// usage
verify(view, lastCall()).showLoadingIndicator(false);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment