Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Junit4 to assertj #673

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
/*
* Copyright 2025 the original author or authors.
* <p>
* Licensed under the Moderne Source Available License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* https://docs.moderne.io/licensing/moderne-source-available-license
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openrewrite.java.testing.assertj;

import lombok.Getter;
import org.jspecify.annotations.Nullable;
import org.openrewrite.Cursor;
import org.openrewrite.ExecutionContext;
import org.openrewrite.Recipe;
import org.openrewrite.SourceFile;
import org.openrewrite.Tree;
import org.openrewrite.TreeVisitor;
import org.openrewrite.java.JavaIsoVisitor;
import org.openrewrite.java.MethodMatcher;
import org.openrewrite.java.search.UsesMethod;
import org.openrewrite.java.tree.J;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public abstract class AbstractJUnitAssertToAssertThatRecipe extends Recipe {
protected static final String ASSERTJ = "org.assertj.core.api.Assertions";
protected static final String ASSERT_THAT = "org.assertj.core.api.Assertions.assertThat";
protected static final String ASSERT_WITHIN = "org.assertj.core.api.Assertions.within";
protected static final String JUNIT4_ASSERT = "org.junit.Assert";
protected static final String JUNIT5_ASSERT = "org.junit.jupiter.api.Assertions";
protected static final String ASSERTJ_CORE = "assertj-core-3.24";
private final String[] methodMatcherSuffix;

protected AbstractJUnitAssertToAssertThatRecipe (String... methodMatcherSuffix) {
this.methodMatcherSuffix = methodMatcherSuffix;
}

protected abstract JUnitAssertionVisitor getJUnitAssertionVisitor(JUnitAssertionConfig config);

protected JUnitAssertionConfig getJunit4Config() {
return new JUnitAssertionConfig(JUNIT4_ASSERT, true, methodMatcherSuffix);
}

protected JUnitAssertionConfig getJunit5Config() {
return new JUnitAssertionConfig(JUNIT5_ASSERT, false, methodMatcherSuffix);
}

@Override
public TreeVisitor<?, ExecutionContext> getVisitor() {
return new TreeVisitor<Tree, ExecutionContext> () {
@Override
public boolean isAcceptable(SourceFile sourceFile, ExecutionContext ctx) {
List<UsesMethod<Object>> usesMethods = Stream.of(getJunit5Config(), getJunit4Config())
.map(JUnitAssertionConfig::getMethodMatcher)
.flatMap(Arrays::stream)
.map(UsesMethod::new)
.collect(Collectors.toList());

return usesMethods.stream().anyMatch(usesMethod -> usesMethod.isAcceptable(sourceFile, ctx));
}
@Override
public @Nullable Tree visit(@Nullable Tree tree, ExecutionContext ctx) {
for (JUnitAssertionConfig assertionConfig : Arrays.asList(getJunit5Config(), getJunit4Config())) {
tree = getJUnitAssertionVisitor(assertionConfig).visit(tree, ctx);
}
return tree;
}

@Override
public @Nullable Tree visit(@Nullable Tree tree, ExecutionContext ctx, Cursor parent) {
for (JUnitAssertionConfig assertionConfig : Arrays.asList(getJunit5Config(), getJunit4Config())) {
tree = getJUnitAssertionVisitor(assertionConfig).visit(tree, ctx, parent);
}
return tree;
}
};
}

@Getter()
public static class JUnitAssertionConfig {

private final String assertionClass;
private final MethodMatcher[] methodMatcher;
private final boolean messageIsFirstArg;

private JUnitAssertionConfig(String assertionClass, boolean messageIsFirstArg, String... methodMatcherSuffix) {
this.assertionClass = assertionClass;
this.messageIsFirstArg = messageIsFirstArg;
this.methodMatcher = Stream.of(methodMatcherSuffix)
.map(pattern -> new MethodMatcher(String.format("%s %s", assertionClass, pattern)))
.toArray(MethodMatcher[]::new);
}

public boolean matches (J.MethodInvocation method) {
return Arrays.stream(methodMatcher).anyMatch(matcher -> matcher.matches(method));
}

}

public abstract static class JUnitAssertionVisitor extends JavaIsoVisitor<ExecutionContext> {
protected final JUnitAssertionConfig config;

protected JUnitAssertionVisitor(JUnitAssertionConfig config) {
this.config = config;
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -16,27 +16,16 @@
package org.openrewrite.java.testing.assertj;

import org.openrewrite.ExecutionContext;
import org.openrewrite.Preconditions;
import org.openrewrite.Recipe;
import org.openrewrite.TreeVisitor;
import org.openrewrite.java.JavaIsoVisitor;
import org.openrewrite.java.JavaParser;
import org.openrewrite.java.JavaTemplate;
import org.openrewrite.java.MethodMatcher;
import org.openrewrite.java.search.UsesMethod;
import org.openrewrite.java.tree.Expression;
import org.openrewrite.java.tree.J;
import org.openrewrite.java.tree.JavaType;
import org.openrewrite.java.tree.TypeUtils;

import java.util.List;

public class JUnitAssertArrayEqualsToAssertThat extends Recipe {

private static final String JUNIT = "org.junit.jupiter.api.Assertions";
private static final String ASSERTJ = "org.assertj.core.api.Assertions";
private static final MethodMatcher ASSERT_ARRAY_EQUALS_MATCHER = new MethodMatcher(JUNIT + " assertArrayEquals(..)", true);

public class JUnitAssertArrayEqualsToAssertThat extends AbstractJUnitAssertToAssertThatRecipe {
@Override
public String getDisplayName() {
return "JUnit `assertArrayEquals` to assertJ";
Expand All @@ -47,56 +36,69 @@ public String getDescription() {
return "Convert JUnit-style `assertArrayEquals()` to AssertJ's `assertThat().contains()` equivalents.";
}

public JUnitAssertArrayEqualsToAssertThat() {
super("assertArrayEquals(..)");
}

@Override
public TreeVisitor<?, ExecutionContext> getVisitor() {
return Preconditions.check(new UsesMethod<>(ASSERT_ARRAY_EQUALS_MATCHER), new JavaIsoVisitor<ExecutionContext>() {
protected JUnitAssertionVisitor getJUnitAssertionVisitor(JUnitAssertionConfig config) {
return new JUnitAssertionVisitor(config) {

@Override
public J.MethodInvocation visitMethodInvocation(J.MethodInvocation method, ExecutionContext ctx) {
J.MethodInvocation md = super.visitMethodInvocation(method, ctx);
if (!ASSERT_ARRAY_EQUALS_MATCHER.matches(md)) {
if (!config.matches(md)) {
return md;
}

maybeAddImport(ASSERTJ, "assertThat", false);
maybeRemoveImport(JUNIT);
maybeRemoveImport(config.getAssertionClass());

List<Expression> args = md.getArguments();
Expression expected = args.get(0);
Expression actual = args.get(1);
if (args.size() == 2) {
Expression expected = args.get(0);
Expression actual = args.get(1);
return JavaTemplate.builder("assertThat(#{anyArray()}).containsExactly(#{anyArray()});")
.staticImports(ASSERTJ + ".assertThat")
.javaParser(JavaParser.fromJavaVersion().classpathFromResources(ctx, "assertj-core-3.24"))
.staticImports(ASSERT_THAT)
.javaParser(JavaParser.fromJavaVersion().classpathFromResources(ctx, ASSERTJ_CORE))
.build()
.apply(getCursor(), md.getCoordinates().replace(), actual, expected);
}
if (args.size() == 3 && isFloatingPointType(args.get(2))) {
Expression expected = args.get(0);
Expression actual = args.get(1);
Expression delta = args.get(2);
maybeAddImport(ASSERTJ, "within", false);
// assert is using floating points with a delta and no message.
return JavaTemplate.builder("assertThat(#{anyArray()}).containsExactly(#{anyArray()}, within(#{any()}));")
.staticImports(ASSERTJ + ".assertThat", ASSERTJ + ".within")
.javaParser(JavaParser.fromJavaVersion().classpathFromResources(ctx, "assertj-core-3.24"))
.staticImports(ASSERT_THAT, ASSERT_WITHIN)
.javaParser(JavaParser.fromJavaVersion().classpathFromResources(ctx, ASSERTJ_CORE))
.build()
.apply(getCursor(), md.getCoordinates().replace(), actual, expected, args.get(2));
.apply(getCursor(), md.getCoordinates().replace(), actual, expected, delta);
}
if (args.size() == 3) {
Expression message = args.get(2);
Expression message = config.isMessageIsFirstArg() ? args.get(0) : args.get(2);
Expression expected = config.isMessageIsFirstArg() ? args.get(1) : args.get(0);
Expression actual = config.isMessageIsFirstArg() ? args.get(2) : args.get(1);
return JavaTemplate.builder("assertThat(#{anyArray()}).as(#{any()}).containsExactly(#{anyArray()});")
.staticImports(ASSERTJ + ".assertThat")
.javaParser(JavaParser.fromJavaVersion().classpathFromResources(ctx, "assertj-core-3.24"))
.staticImports(ASSERT_THAT)
.javaParser(JavaParser.fromJavaVersion().classpathFromResources(ctx, ASSERTJ_CORE))
.build()
.apply(getCursor(), md.getCoordinates().replace(), actual, message, expected);
}

maybeAddImport(ASSERTJ, "within", false);

// The assertEquals is using a floating point with a delta argument and a message.
Expression message = args.get(3);
Expression message = config.isMessageIsFirstArg() ? args.get(0) : args.get(3);
Expression expected = config.isMessageIsFirstArg() ? args.get(1) : args.get(0);
Expression actual = config.isMessageIsFirstArg() ? args.get(2) : args.get(1);
Expression delta = config.isMessageIsFirstArg() ? args.get(3) : args.get(2);
return JavaTemplate.builder("assertThat(#{anyArray()}).as(#{any()}).containsExactly(#{anyArray()}, within(#{}));")
.staticImports(ASSERTJ + ".assertThat", ASSERTJ + ".within")
.javaParser(JavaParser.fromJavaVersion().classpathFromResources(ctx, "assertj-core-3.24"))
.staticImports(ASSERT_THAT, ASSERT_WITHIN)
.javaParser(JavaParser.fromJavaVersion().classpathFromResources(ctx, ASSERTJ_CORE))
.build()
.apply(getCursor(), md.getCoordinates().replace(), actual, message, expected, args.get(2));
.apply(getCursor(), md.getCoordinates().replace(), actual, message, expected, delta);
}

/**
Expand All @@ -115,6 +117,6 @@ private boolean isFloatingPointType(Expression expression) {
JavaType.Primitive parameterType = TypeUtils.asPrimitive(expression.getType());
return parameterType == JavaType.Primitive.Double || parameterType == JavaType.Primitive.Float;
}
});
};
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,26 +16,16 @@
package org.openrewrite.java.testing.assertj;

import org.openrewrite.ExecutionContext;
import org.openrewrite.Preconditions;
import org.openrewrite.Recipe;
import org.openrewrite.TreeVisitor;
import org.openrewrite.java.JavaIsoVisitor;
import org.openrewrite.java.JavaParser;
import org.openrewrite.java.JavaTemplate;
import org.openrewrite.java.MethodMatcher;
import org.openrewrite.java.search.UsesMethod;
import org.openrewrite.java.tree.Expression;
import org.openrewrite.java.tree.J;
import org.openrewrite.java.tree.JavaType;
import org.openrewrite.java.tree.TypeUtils;

import java.util.List;

public class JUnitAssertEqualsToAssertThat extends Recipe {

private static final String JUNIT = "org.junit.jupiter.api.Assertions";
private static final String ASSERTJ = "org.assertj.core.api.Assertions";
private static final MethodMatcher ASSERT_EQUALS_MATCHER = new MethodMatcher(JUNIT + " assertEquals(..)", true);
public class JUnitAssertEqualsToAssertThat extends AbstractJUnitAssertToAssertThatRecipe {

@Override
public String getDisplayName() {
Expand All @@ -47,57 +37,69 @@ public String getDescription() {
return "Convert JUnit-style `assertEquals()` to AssertJ's `assertThat().isEqualTo()`.";
}

public JUnitAssertEqualsToAssertThat() {
super("assertEquals(..)");
}

@Override
public TreeVisitor<?, ExecutionContext> getVisitor() {
return Preconditions.check(new UsesMethod<>(ASSERT_EQUALS_MATCHER), new JavaIsoVisitor<ExecutionContext>() {
protected JUnitAssertionVisitor getJUnitAssertionVisitor(JUnitAssertionConfig config) {
return new JUnitAssertionVisitor(config) {

@Override
public J.MethodInvocation visitMethodInvocation(J.MethodInvocation method, ExecutionContext ctx) {
J.MethodInvocation mi = super.visitMethodInvocation(method, ctx);
if (!ASSERT_EQUALS_MATCHER.matches(mi)) {
if (!config.matches(mi)) {
return mi;
}

maybeAddImport(ASSERTJ, "assertThat", false);
maybeRemoveImport(JUNIT);
maybeRemoveImport(config.getAssertionClass());

List<Expression> args = mi.getArguments();
Expression expected = args.get(0);
Expression actual = args.get(1);
if (args.size() == 2) {
Expression expected = args.get(0);
Expression actual = args.get(1);
return JavaTemplate.builder("assertThat(#{any()}).isEqualTo(#{any()});")
.staticImports(ASSERTJ + ".assertThat")
.javaParser(JavaParser.fromJavaVersion().classpathFromResources(ctx, "assertj-core-3.24"))
.staticImports(ASSERT_THAT)
.javaParser(JavaParser.fromJavaVersion().classpathFromResources(ctx, ASSERTJ_CORE))
.build()
.apply(getCursor(), mi.getCoordinates().replace(), actual, expected);
}
if (args.size() == 3 && !isFloatingPointType(args.get(2))) {
Expression message = args.get(2);
if (args.size() == 3 && !isFloatingPointType(config.isMessageIsFirstArg() ? args.get(0) : args.get(2))) {
Expression message = config.isMessageIsFirstArg() ? args.get(0) : args.get(2);
Expression expected = config.isMessageIsFirstArg() ? args.get(1) : args.get(0);
Expression actual = config.isMessageIsFirstArg() ? args.get(2) : args.get(1);
return JavaTemplate.builder("assertThat(#{any()}).as(#{any()}).isEqualTo(#{any()});")
.staticImports(ASSERTJ + ".assertThat")
.staticImports(ASSERT_THAT)
.imports("java.util.function.Supplier")
.javaParser(JavaParser.fromJavaVersion().classpathFromResources(ctx, "assertj-core-3.24"))
.javaParser(JavaParser.fromJavaVersion().classpathFromResources(ctx, ASSERTJ_CORE))
.build()
.apply(getCursor(), mi.getCoordinates().replace(), actual, message, expected);
}
if (args.size() == 3) {
Expression expected = args.get(0);
Expression actual = args.get(1);
maybeAddImport(ASSERTJ, "within", false);
return JavaTemplate.builder("assertThat(#{any()}).isCloseTo(#{any()}, within(#{any()}));")
.staticImports(ASSERTJ + ".assertThat", ASSERTJ + ".within")
.javaParser(JavaParser.fromJavaVersion().classpathFromResources(ctx, "assertj-core-3.24"))
.staticImports(ASSERT_THAT, ASSERT_WITHIN)
.javaParser(JavaParser.fromJavaVersion().classpathFromResources(ctx, ASSERTJ_CORE))
.build()
.apply(getCursor(), mi.getCoordinates().replace(), actual, expected, args.get(2));
}

maybeAddImport(ASSERTJ, "within", false);

// The assertEquals is using a floating point with a delta argument and a message.
Expression message = args.get(3);
Expression message = config.isMessageIsFirstArg() ? args.get(0) : args.get(3);
Expression expected = config.isMessageIsFirstArg() ? args.get(1) : args.get(0);
Expression actual = config.isMessageIsFirstArg() ? args.get(2) : args.get(1);
Expression delta = config.isMessageIsFirstArg() ? args.get(3) : args.get(2);
return JavaTemplate.builder("assertThat(#{any()}).as(#{any()}).isCloseTo(#{any()}, within(#{any()}));")
.staticImports(ASSERTJ + ".assertThat", ASSERTJ + ".within")
.staticImports(ASSERT_THAT, ASSERT_WITHIN)
.imports("java.util.function.Supplier")
.javaParser(JavaParser.fromJavaVersion().classpathFromResources(ctx, "assertj-core-3.24"))
.javaParser(JavaParser.fromJavaVersion().classpathFromResources(ctx, ASSERTJ_CORE))
.build()
.apply(getCursor(), mi.getCoordinates().replace(), actual, message, expected, args.get(2));
.apply(getCursor(), mi.getCoordinates().replace(), actual, message, expected, delta);
}

private boolean isFloatingPointType(Expression expression) {
Expand All @@ -110,6 +112,6 @@ private boolean isFloatingPointType(Expression expression) {
JavaType.Primitive parameterType = TypeUtils.asPrimitive(expression.getType());
return parameterType == JavaType.Primitive.Double || parameterType == JavaType.Primitive.Float;
}
});
};
}
}
Loading