use of com.google.errorprone.fixes.SuggestedFix in project mockito by mockito.
the class AbstractMockitoAnyForPrimitiveType method matchMethodInvocation.
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (!matcher().matches(tree, state)) {
return NO_MATCH;
}
MethodSymbol method = ASTHelpers.getSymbol(tree);
Type matcherType = method.getReturnType();
// It is expected that the call to anyX() is itself the argument to another call which is
// the one being mocked, e.g. something like this:
// when(mock.call(..., anyInt(), ...))...
TreePath path = state.getPath();
Tree parentTree = path.getParentPath().getLeaf();
if (!(parentTree instanceof MethodInvocationTree)) {
// TODO: Support casting.
return NO_MATCH;
}
MethodInvocationTree parentCall = (MethodInvocationTree) parentTree;
MethodSymbol parentMethod = ASTHelpers.getSymbol(parentCall);
// Find the index of the argument in the parent call.
int argumentIndex = -1;
List<? extends ExpressionTree> parentArguments = parentCall.getArguments();
for (int i = 0; i < parentArguments.size(); i++) {
ExpressionTree argumentTree = parentArguments.get(i);
if (argumentTree == tree) {
argumentIndex = i;
break;
}
}
if (argumentIndex == -1) {
throw new IllegalStateException("Cannot find argument " + state.getSourceForNode(tree) + " in argument list from " + state.getSourceForNode(parentTree));
}
Type parameterType = getParameterType(parentMethod, argumentIndex);
TypeKind parameterTypeKind = parameterType.getKind();
if (parameterTypeKind.isPrimitive() && parameterTypeKind != matcherType.getKind()) {
String expectedTypeAsString = parameterType.toString();
String replacementName = "any" + Character.toUpperCase(expectedTypeAsString.charAt(0)) + expectedTypeAsString.substring(1);
String message = formatMessage(expectedTypeAsString, matcherType, replacementName);
SuggestedFix.Builder fixBuilder = SuggestedFix.builder();
ExpressionTree methodSelect = tree.getMethodSelect();
String replacement;
if (methodSelect instanceof MemberSelectTree) {
MemberSelectTree qualifier = (MemberSelectTree) methodSelect;
replacement = state.getSourceForNode(qualifier.getExpression()) + "." + replacementName;
} else {
replacement = replacementName;
String staticImport = method.owner + "." + replacementName;
fixBuilder.addStaticImport(staticImport);
}
SuggestedFix fix = fixBuilder.replace(tree, replacement + "()").build();
return buildDescription(tree).setMessage(message).addFix(fix).build();
}
return NO_MATCH;
}
Aggregations