Skip to content

Commit

Permalink
Extract method matchers to constants
Browse files Browse the repository at this point in the history
  • Loading branch information
timtebeek committed Nov 17, 2024
1 parent 4e91f08 commit b310b27
Showing 1 changed file with 13 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -41,16 +41,16 @@ public String getDescription() {
"or assertFalse with a boolean comparison.";
}

private static final MethodMatcher ASSERT_TRUE_MATCHER = new MethodMatcher("org.junit.jupiter.api.Assertions assertTrue(..)");
private static final MethodMatcher ASSERT_FALSE_MATCHER = new MethodMatcher("org.junit.jupiter.api.Assertions assertFalse(..)");

@Override
public TreeVisitor<?, ExecutionContext> getVisitor() {
MethodMatcher assertTrueMatcher = new MethodMatcher("org.junit.jupiter.api.Assertions assertTrue(..)");
MethodMatcher assertFalseMatcher = new MethodMatcher("org.junit.jupiter.api.Assertions assertFalse(..)");
TreeVisitor<?, ExecutionContext> orMatcher = Preconditions.or(new UsesMethod<>(assertTrueMatcher), new UsesMethod<>(assertFalseMatcher));
return Preconditions.check(orMatcher, new JavaIsoVisitor<ExecutionContext>() {
JavaIsoVisitor<ExecutionContext> visitor = new JavaIsoVisitor<ExecutionContext>() {
@Override
public J.MethodInvocation visitMethodInvocation(J.MethodInvocation methodInvocation, ExecutionContext ctx) {
J.MethodInvocation mi = super.visitMethodInvocation(methodInvocation, ctx);
if (!assertTrueMatcher.matches(mi) && !assertFalseMatcher.matches(mi)) {
if (!ASSERT_TRUE_MATCHER.matches(mi) && !ASSERT_FALSE_MATCHER.matches(mi)) {
return mi;
}

Expand All @@ -62,13 +62,13 @@ public J.MethodInvocation visitMethodInvocation(J.MethodInvocation methodInvocat
if (binary.getOperator() != J.Binary.Type.Equal && binary.getOperator() != J.Binary.Type.NotEqual) {
return mi;
}
boolean positive = binary.getOperator() == J.Binary.Type.Equal == assertTrueMatcher.matches(mi);
List<Expression> newArguments = new ArrayList<>();
newArguments.add(binary.getLeft());
newArguments.add(binary.getRight());
newArguments.addAll(mi.getArguments().subList(1, mi.getArguments().size()));

String newMethodName = positive ? "assertSame" : "assertNotSame";
String newMethodName = binary.getOperator() == J.Binary.Type.Equal == ASSERT_TRUE_MATCHER.matches(mi) ?
"assertSame" : "assertNotSame";

maybeRemoveImport("org.junit.jupiter.api.Assertions");
maybeAddImport("org.junit.jupiter.api.Assertions", newMethodName);
Expand All @@ -78,7 +78,12 @@ public J.MethodInvocation visitMethodInvocation(J.MethodInvocation methodInvocat
.withMethodType(newType)
.withArguments(newArguments);
}
});
};
return Preconditions.check(
Preconditions.or(
new UsesMethod<>(ASSERT_TRUE_MATCHER),
new UsesMethod<>(ASSERT_FALSE_MATCHER)),
visitor);
}

}

0 comments on commit b310b27

Please sign in to comment.