diff --git a/src/main/java/org/openrewrite/java/testing/assertj/IsEqualToBoolean.java b/src/main/java/org/openrewrite/java/testing/assertj/IsEqualToBoolean.java
deleted file mode 100644
index d5dec1d0c..000000000
--- a/src/main/java/org/openrewrite/java/testing/assertj/IsEqualToBoolean.java
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * Copyright 2024 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * 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 org.openrewrite.ExecutionContext;
-import org.openrewrite.Preconditions;
-import org.openrewrite.Recipe;
-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 org.openrewrite.java.tree.J.MethodInvocation;
-import org.openrewrite.java.tree.JavaType.Method;
-
-import java.util.Collections;
-
-/**
- * AssertJ has a more idiomatic way of asserting that a boolean is true. This
- * recipe will find instances of:
- *
- * -`assertThat(boolean).isEqualTo(true)` and replace them with `isTrue()`.
- * -`assertThat(boolean).isEqualTo(false)` and replace them with `isFalse()`.
- */
-public class IsEqualToBoolean extends Recipe {
-
- private static final MethodMatcher IS_EQUAL_TO = new MethodMatcher(
- "org.assertj.core.api.AbstractBooleanAssert isEqualTo(boolean)");
-
- @Override
- public String getDisplayName() {
- return "Convert `assertThat(String).isEqualTo(true)` to `isTrue()` and `isEqualTo(false)` to `isFalse()`";
- }
-
- @Override
- public String getDescription() {
- return "Adopt idiomatic AssertJ assertion for true booleans.";
- }
-
- @Override
- public TreeVisitor, ExecutionContext> getVisitor() {
- return Preconditions.check(new UsesMethod<>(IS_EQUAL_TO), new JavaIsoVisitor() {
- @Override
- public J.MethodInvocation visitMethodInvocation(J.MethodInvocation method, ExecutionContext ctx) {
- MethodInvocation mi = super.visitMethodInvocation(method, ctx);
- if (IS_EQUAL_TO.matches(mi)) {
- String methodName;
- if (J.Literal.isLiteralValue(mi.getArguments().get(0), true)) {
- methodName = "isTrue";
- } else if (J.Literal.isLiteralValue(mi.getArguments().get(0), false)) {
- methodName = "isFalse";
- } else {
- return mi;
- }
- Method isBooleanMethod = mi.getMethodType().withName(methodName);
- return mi.withName(mi.getName().withSimpleName(methodName).withType(isBooleanMethod))
- .withMethodType(isBooleanMethod).withArguments(Collections.emptyList());
- }
- return mi;
- }
- });
- }
-}
diff --git a/src/main/java/org/openrewrite/java/testing/assertj/IsEqualToEmptyString.java b/src/main/java/org/openrewrite/java/testing/assertj/IsEqualToEmptyString.java
deleted file mode 100644
index fb014fd94..000000000
--- a/src/main/java/org/openrewrite/java/testing/assertj/IsEqualToEmptyString.java
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * Copyright 2024 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * 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 org.openrewrite.ExecutionContext;
-import org.openrewrite.Preconditions;
-import org.openrewrite.Recipe;
-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 org.openrewrite.java.tree.JavaType;
-
-import java.util.Collections;
-
-/**
- * AssertJ has a more idiomatic way of asserting that a String is empty.
- * This recipe will find instances of `assertThat(String).isEqualTo("")` and replace them with `isEmpty()`.
- */
-public class IsEqualToEmptyString extends Recipe {
-
- private static final MethodMatcher IS_EQUAL_TO = new MethodMatcher("org.assertj.core.api.AbstractStringAssert isEqualTo(java.lang.String)");
-
- @Override
- public String getDisplayName() {
- return "Convert `assertThat(String).isEqualTo(\"\")` to `isEmpty()`";
- }
-
- @Override
- public String getDescription() {
- return "Adopt idiomatic AssertJ assertion for empty Strings.";
- }
-
- @Override
- public TreeVisitor, ExecutionContext> getVisitor() {
- return Preconditions.check(
- new UsesMethod<>(IS_EQUAL_TO),
- new JavaIsoVisitor() {
- @Override
- public J.MethodInvocation visitMethodInvocation(J.MethodInvocation method, ExecutionContext ctx) {
- J.MethodInvocation mi = super.visitMethodInvocation(method, ctx);
- if (IS_EQUAL_TO.matches(mi) && J.Literal.isLiteralValue(mi.getArguments().get(0), "")) {
- JavaType.Method isEmptyMethodType = mi.getMethodType().withName("isEmpty");
- return mi
- .withName(mi.getName().withSimpleName("isEmpty").withType(isEmptyMethodType))
- .withMethodType(isEmptyMethodType)
- .withArguments(Collections.emptyList());
- }
- return mi;
- }
- }
- );
- }
-}
diff --git a/src/main/java/org/openrewrite/java/testing/assertj/SimplifyAssertJAssertion.java b/src/main/java/org/openrewrite/java/testing/assertj/SimplifyAssertJAssertion.java
new file mode 100644
index 000000000..391a9e3f4
--- /dev/null
+++ b/src/main/java/org/openrewrite/java/testing/assertj/SimplifyAssertJAssertion.java
@@ -0,0 +1,105 @@
+/*
+ * Copyright 2023 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * 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.AllArgsConstructor;
+import lombok.NoArgsConstructor;
+import org.openrewrite.ExecutionContext;
+import org.openrewrite.Option;
+import org.openrewrite.Recipe;
+import org.openrewrite.TreeVisitor;
+import org.openrewrite.internal.lang.Nullable;
+import org.openrewrite.java.JavaIsoVisitor;
+import org.openrewrite.java.JavaParser;
+import org.openrewrite.java.JavaTemplate;
+import org.openrewrite.java.MethodMatcher;
+import org.openrewrite.java.tree.J;
+import org.openrewrite.java.tree.TypeUtils;
+
+@AllArgsConstructor
+@NoArgsConstructor
+public class SimplifyAssertJAssertion extends Recipe {
+
+ @Option(displayName = "AssertJ assertion",
+ description = "The assertion method that should be replaced.",
+ example = "hasSize",
+ required = false)
+ @Nullable
+ String assertToReplace;
+
+ @Option(displayName = "Assertion argument literal",
+ description = "The literal argument passed into the assertion to replace; use \"null\" for `null`.",
+ example = "0")
+ String literalArgument;
+
+ @Option(displayName = "Dedicated assertion",
+ description = "The zero argument assertion to adopt instead.",
+ example = "isEmpty")
+ String dedicatedAssertion;
+
+ @Option(displayName = "Required type",
+ description = "The type of the actual assertion argument.",
+ example = "java.lang.String")
+ String requiredType;
+
+ @Override
+ public String getDisplayName() {
+ return "Simplify AssertJ assertions with literal arguments";
+ }
+
+ @Override
+ public String getDescription() {
+ return "Simplify AssertJ assertions by replacing them with more expressiove dedicated assertions.";
+ }
+
+ @Override
+ public TreeVisitor, ExecutionContext> getVisitor() {
+ return new ShorthenChainedAssertJAssertionsVisitor();
+ }
+
+ private class ShorthenChainedAssertJAssertionsVisitor extends JavaIsoVisitor {
+ private final MethodMatcher ASSERT_THAT_MATCHER = new MethodMatcher("org.assertj.core.api.Assertions assertThat(..)");
+ private final MethodMatcher ASSERT_TO_REPLACE = new MethodMatcher("org.assertj.core.api.* " + assertToReplace + "(..)");
+
+ @Override
+ public J.MethodInvocation visitMethodInvocation(J.MethodInvocation methodInvocation, ExecutionContext ctx) {
+ J.MethodInvocation mi = super.visitMethodInvocation(methodInvocation, ctx);
+
+ // Match the end of the chain first, then the select to avoid matching the wrong method chain
+ if (!ASSERT_TO_REPLACE.matches(mi) || !ASSERT_THAT_MATCHER.matches(mi.getSelect())) {
+ return mi;
+ }
+
+ // Compare argument with passed in literal
+ if (!(mi.getArguments().get(0) instanceof J.Literal) ||
+ !literalArgument.equals(((J.Literal) mi.getArguments().get(0)).getValueSource())) { // Implies "null" is `null`
+ return mi;
+ }
+
+ // Check argument type of assertThat
+ if (!TypeUtils.isAssignableTo(requiredType, ((J.MethodInvocation) mi.getSelect()).getArguments().get(0).getType())) {
+ return mi;
+ }
+
+ // Assume zero argument replacement method
+ return JavaTemplate.builder(dedicatedAssertion + "()")
+ .contextSensitive()
+ .javaParser(JavaParser.fromJavaVersion().classpathFromResources(ctx, "assertj-core-3.24"))
+ .build()
+ .apply(getCursor(), mi.getCoordinates().replaceMethod());
+ }
+ }
+}
diff --git a/src/main/java/org/openrewrite/java/testing/assertj/SimplifyChainedAssertJAssertion.java b/src/main/java/org/openrewrite/java/testing/assertj/SimplifyChainedAssertJAssertion.java
index 881bce47a..d84b1179a 100644
--- a/src/main/java/org/openrewrite/java/testing/assertj/SimplifyChainedAssertJAssertion.java
+++ b/src/main/java/org/openrewrite/java/testing/assertj/SimplifyChainedAssertJAssertion.java
@@ -38,29 +38,29 @@
@AllArgsConstructor
@NoArgsConstructor
public class SimplifyChainedAssertJAssertion extends Recipe {
- @Option(displayName = "AssertJ Assertion",
+ @Option(displayName = "AssertJ chained assertion",
description = "The chained AssertJ assertion to move to dedicated assertion.",
example = "equals",
required = false)
@Nullable
String chainedAssertion;
- @Option(displayName = "AssertJ Assertion",
+ @Option(displayName = "AssertJ replaced assertion",
description = "The AssertJ assert that should be replaced.",
example = "isTrue",
required = false)
@Nullable
String assertToReplace;
- @Option(displayName = "AssertJ Assertion",
+ @Option(displayName = "AssertJ replacement assertion",
description = "The AssertJ method to migrate to.",
example = "isEqualTo",
required = false)
@Nullable
String dedicatedAssertion;
- @Option(displayName = "Required Type",
- description = "Specifies the type the recipe should run on.",
+ @Option(displayName = "Required type",
+ description = "The type of the actual assertion argument.",
example = "java.lang.String",
required = false)
@Nullable
@@ -120,11 +120,6 @@ public J.MethodInvocation visitMethodInvocation(J.MethodInvocation methodInvocat
List arguments = new ArrayList<>();
arguments.add(actual);
- // Special case for more expressive assertions: assertThat(x.size()).isEqualTo(0) -> isEmpty()
- if ("size".equals(chainedAssertion) && "isEqualTo".equals(assertToReplace) && hasZeroArgument(mi)) {
- return applyTemplate("assertThat(#{any()}).isEmpty()", arguments, mi, ctx);
- }
-
String template = getStringTemplateAndAppendArguments(assertThatArg, mi, arguments);
return applyTemplate(String.format(template, dedicatedAssertion), arguments, mi, ctx);
}
@@ -136,38 +131,38 @@ private J.MethodInvocation applyTemplate(String formattedTemplate, List arguments) {
- Expression assertThatArgument = assertThatArg.getArguments().get(0);
- Expression methodToReplaceArgument = methodToReplace.getArguments().get(0);
- boolean assertThatArgumentIsEmpty = assertThatArgument instanceof J.Empty;
- boolean methodToReplaceArgumentIsEmpty = methodToReplaceArgument instanceof J.Empty;
+ private String getStringTemplateAndAppendArguments(J.MethodInvocation assertThatArg, J.MethodInvocation methodToReplace, List arguments) {
+ Expression assertThatArgument = assertThatArg.getArguments().get(0);
+ Expression methodToReplaceArgument = methodToReplace.getArguments().get(0);
+ boolean assertThatArgumentIsEmpty = assertThatArgument instanceof J.Empty;
+ boolean methodToReplaceArgumentIsEmpty = methodToReplaceArgument instanceof J.Empty;
- // If both arguments are empty, then the select is already added to the arguments list, and we use a minimal template
- if (assertThatArgumentIsEmpty && methodToReplaceArgumentIsEmpty) {
- return "assertThat(#{any()}).%s()";
- }
-
- // If both arguments are not empty, then we add both to the arguments to the arguments list, and return a template with two arguments
- if (!assertThatArgumentIsEmpty && !methodToReplaceArgumentIsEmpty) {
- // This should only happen for map assertions using a key and value
- arguments.add(assertThatArgument);
- arguments.add(methodToReplaceArgument);
- return "assertThat(#{any()}).%s(#{any()}, #{any()})";
- }
+ // If both arguments are empty, then the select is already added to the arguments list, and we use a minimal template
+ if (assertThatArgumentIsEmpty && methodToReplaceArgumentIsEmpty) {
+ return "assertThat(#{any()}).%s()";
+ }
- // If either argument is empty, we choose which one to add to the arguments list, and optionally extract the select
- arguments.add(extractEitherArgument(assertThatArgumentIsEmpty, assertThatArgument, methodToReplaceArgument));
+ // If both arguments are not empty, then we add both to the arguments to the arguments list, and return a template with two arguments
+ if (!assertThatArgumentIsEmpty && !methodToReplaceArgumentIsEmpty) {
+ // This should only happen for map assertions using a key and value
+ arguments.add(assertThatArgument);
+ arguments.add(methodToReplaceArgument);
+ return "assertThat(#{any()}).%s(#{any()}, #{any()})";
+ }
- // Special case for Path.of() assertions
- if ("java.nio.file.Path".equals(requiredType) && dedicatedAssertion.contains("Raw")
- && TypeUtils.isAssignableTo("java.lang.String", assertThatArgument.getType())) {
- return "assertThat(#{any()}).%s(Path.of(#{any()}))";
- }
+ // If either argument is empty, we choose which one to add to the arguments list, and optionally extract the select
+ arguments.add(extractEitherArgument(assertThatArgumentIsEmpty, assertThatArgument, methodToReplaceArgument));
- return "assertThat(#{any()}).%s(#{any()})";
+ // Special case for Path.of() assertions
+ if ("java.nio.file.Path".equals(requiredType) && dedicatedAssertion.contains("Raw")
+ && TypeUtils.isAssignableTo("java.lang.String", assertThatArgument.getType())) {
+ maybeAddImport("java.nio.file.Path");
+ return "assertThat(#{any()}).%s(Path.of(#{any()}))";
+ }
+ return "assertThat(#{any()}).%s(#{any()})";
+ }
}
private static Expression extractEitherArgument(boolean assertThatArgumentIsEmpty, Expression assertThatArgument, Expression methodToReplaceArgument) {
@@ -183,13 +178,4 @@ private static Expression extractEitherArgument(boolean assertThatArgumentIsEmpt
}
return assertThatArgument;
}
-
- private boolean hasZeroArgument(J.MethodInvocation method) {
- List arguments = method.getArguments();
- if (arguments.size() == 1 && arguments.get(0) instanceof J.Literal) {
- J.Literal literalArg = (J.Literal) arguments.get(0);
- return literalArg.getValue() != null && literalArg.getValue().equals(0);
- }
- return false;
- }
}
diff --git a/src/main/resources/META-INF/rewrite/assertj.yml b/src/main/resources/META-INF/rewrite/assertj.yml
index e07c9bfb6..7dcfc91b9 100644
--- a/src/main/resources/META-INF/rewrite/assertj.yml
+++ b/src/main/resources/META-INF/rewrite/assertj.yml
@@ -25,9 +25,8 @@ recipeList:
- org.openrewrite.java.testing.hamcrest.MigrateHamcrestToAssertJ
- org.openrewrite.java.testing.assertj.JUnitToAssertj
- org.openrewrite.java.testing.assertj.StaticImports
- - org.openrewrite.java.testing.assertj.IsEqualToBoolean
- org.openrewrite.java.testing.assertj.SimplifyChainedAssertJAssertions
- - org.openrewrite.java.testing.assertj.IsEqualToEmptyString
+ - org.openrewrite.java.testing.assertj.SimplifyAssertJAssertions
- tech.picnic.errorprone.refasterrules.AssertJBigDecimalRulesRecipes
- tech.picnic.errorprone.refasterrules.AssertJBigIntegerRulesRecipes
@@ -67,7 +66,7 @@ recipeList:
type: specs.openrewrite.org/v1beta/recipe
name: org.openrewrite.java.testing.assertj.SimplifyChainedAssertJAssertions
displayName: Simplify AssertJ chained assertions
-description: Replace AssertJ chained assertions with dedicated assertions that function the same.
+description: Replace AssertJ assertions where a method is called on the actual value with a dedicated assertion.
tags:
- testing
- assertj
@@ -364,11 +363,67 @@ recipeList:
assertToReplace: isFalse
dedicatedAssertion: isExhausted
requiredType: java.util.Iterator
+ # Object assertions
- org.openrewrite.java.testing.assertj.SimplifyChainedAssertJAssertion:
chainedAssertion: toString
assertToReplace: isEqualTo
dedicatedAssertion: hasToString
requiredType: java.lang.Object
+ - org.openrewrite.java.testing.assertj.SimplifyChainedAssertJAssertion:
+ chainedAssertion: equals
+ assertToReplace: isTrue
+ dedicatedAssertion: isEqualTo
+ requiredType: java.lang.Object
+
+---
+type: specs.openrewrite.org/v1beta/recipe
+name: org.openrewrite.java.testing.assertj.SimplifyAssertJAssertions
+displayName: Shorten AssertJ assertions
+description: Replace AssertJ assertions where a dedicated assertion is available for the same actual value.
+tags:
+ - testing
+ - assertj
+recipeList:
+ - org.openrewrite.java.testing.assertj.SimplifyAssertJAssertion:
+ assertToReplace: isEqualTo
+ literalArgument: "null"
+ dedicatedAssertion: isNull
+ requiredType: java.lang.Object
+ - org.openrewrite.java.testing.assertj.SimplifyAssertJAssertion:
+ assertToReplace: isEqualTo
+ literalArgument: true
+ dedicatedAssertion: isTrue
+ requiredType: java.lang.Boolean
+ - org.openrewrite.java.testing.assertj.SimplifyAssertJAssertion:
+ assertToReplace: isEqualTo
+ literalArgument: '""'
+ dedicatedAssertion: isEmpty
+ requiredType: java.lang.String
+ - org.openrewrite.java.testing.assertj.SimplifyAssertJAssertion:
+ assertToReplace: isEqualTo
+ literalArgument: false
+ dedicatedAssertion: isFalse
+ requiredType: java.lang.Boolean
+ - org.openrewrite.java.testing.assertj.SimplifyAssertJAssertion:
+ assertToReplace: hasSize
+ literalArgument: 0
+ dedicatedAssertion: isEmpty
+ requiredType: java.lang.String
+ - org.openrewrite.java.testing.assertj.SimplifyAssertJAssertion:
+ assertToReplace: hasSize
+ literalArgument: 0
+ dedicatedAssertion: isEmpty
+ requiredType: java.io.File
+ - org.openrewrite.java.testing.assertj.SimplifyAssertJAssertion:
+ assertToReplace: hasSize
+ literalArgument: 0
+ dedicatedAssertion: isEmpty
+ requiredType: java.util.Collection
+ - org.openrewrite.java.testing.assertj.SimplifyAssertJAssertion:
+ assertToReplace: hasSize
+ literalArgument: 0
+ dedicatedAssertion: isEmpty
+ requiredType: java.util.Map
---
type: specs.openrewrite.org/v1beta/recipe
diff --git a/src/test/java/org/openrewrite/java/testing/assertj/AssertJBestPracticesTest.java b/src/test/java/org/openrewrite/java/testing/assertj/AssertJBestPracticesTest.java
index 4252b33ff..f96060d54 100644
--- a/src/test/java/org/openrewrite/java/testing/assertj/AssertJBestPracticesTest.java
+++ b/src/test/java/org/openrewrite/java/testing/assertj/AssertJBestPracticesTest.java
@@ -15,29 +15,39 @@
*/
package org.openrewrite.java.testing.assertj;
+import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
import org.openrewrite.DocumentExample;
import org.openrewrite.InMemoryExecutionContext;
+import org.openrewrite.Issue;
import org.openrewrite.java.JavaParser;
import org.openrewrite.test.RecipeSpec;
import org.openrewrite.test.RewriteTest;
+import java.util.stream.Stream;
+
+import static org.junit.jupiter.params.provider.Arguments.arguments;
import static org.openrewrite.java.Assertions.java;
class AssertJBestPracticesTest implements RewriteTest {
@Override
public void defaults(RecipeSpec spec) {
- spec
- .parser(JavaParser.fromJavaVersion().classpathFromResources(new InMemoryExecutionContext(), "assertj-core-3.24"))
+ spec.parser(
+ JavaParser.fromJavaVersion()
+ .classpathFromResources(new InMemoryExecutionContext(), "assertj-core-3.24"))
.recipeFromResources("org.openrewrite.java.testing.assertj.Assertj");
}
@DocumentExample
@Test
+ @SuppressWarnings("DataFlowIssue")
void convertsIsEqualToEmptyString() {
rewriteRun(
- //language=java
+ // language=java
java(
"""
import static org.assertj.core.api.Assertions.assertThat;
@@ -58,4 +68,255 @@ void test() {
)
);
}
+
+ @Test
+ @Issue("https://github.com/openrewrite/rewrite-testing-frameworks/issues/398")
+ void sizeIsEqualToZeroToIsEmpty() {
+ //language=java
+ rewriteRun(
+ java(
+ """
+ import java.util.List;
+
+ import static org.assertj.core.api.Assertions.assertThat;
+
+ class MyTest {
+ void testMethod(List list) {
+ assertThat(list.size()).isEqualTo(0);
+ }
+ }
+ """,
+ """
+ import java.util.List;
+
+ import static org.assertj.core.api.Assertions.assertThat;
+
+ class MyTest {
+ void testMethod(List list) {
+ assertThat(list).isEmpty();
+ }
+ }
+ """
+ )
+ );
+ }
+
+ /**
+ * Chained AssertJ assertions should be simplified to the corresponding dedicated assertion, as
+ * per java:S5838
+ */
+ @Nested
+ class SonarDedicatedAssertions {
+ private static Stream replacements() {
+ return Stream.of(
+ // Related to Object
+ arguments("Object", "assertThat(x).isEqualTo(null)", "assertThat(x).isNull()"),
+ arguments("Boolean", "assertThat(x).isEqualTo(true)", "assertThat(x).isTrue()"),
+ arguments("Boolean", "assertThat(x).isEqualTo(false)", "assertThat(x).isFalse()"),
+ arguments("Object", "assertThat(x.equals(y)).isTrue()", "assertThat(x).isEqualTo(y)"),
+// arguments("Object", "assertThat(x == y).isTrue()", "assertThat(x).isSameAs(y)"),
+// arguments("Object", "assertThat(x == null).isTrue()", "assertThat(x).isNull()"),
+ arguments(
+ "Object",
+ "assertThat(x.toString()).isEqualTo(\"y\")",
+ "assertThat(x).hasToString(\"y\")"),
+// arguments(
+// "Object",
+// "assertThat(x.hashCode()).isEqualTo(y.hashCode())",
+// "assertThat(x).hasSameHashCodeAs(y)"),
+// arguments(
+// "Object",
+// "assertThat(x instanceof String).isTrue()",
+// "assertThat(x).isInstanceOf(String.class)"),
+ // Related to Comparable
+// arguments(
+// "java.math.BigDecimal",
+// "assertThat(x.compareTo(y)).isZero()",
+// "assertThat(x).isEqualByComparingTo(y)"),
+// arguments(
+// "int", "assertThat(x >= y).isTrue()", "assertThat(x).isGreaterThanOrEqualTo(y)"),
+// arguments("long", "assertThat(x > y).isTrue()", "assertThat(x).isGreaterThan(y)"),
+// arguments(
+// "double", "assertThat(x <= y).isTrue()", "assertThat(x).isLessThanOrEqualTo(y)"),
+// arguments("float", "assertThat(x < y).isTrue()", "assertThat(x).isLessThan(y)"),
+ // Related to String
+ arguments("String", "assertThat(x.isEmpty()).isTrue()", "assertThat(x).isEmpty()"),
+ arguments("String", "assertThat(x).hasSize(0)", "assertThat(x).isEmpty()"),
+ arguments("String", "assertThat(x.equals(y)).isTrue()", "assertThat(x).isEqualTo(y)"),
+ arguments(
+ "String",
+ "assertThat(x.equalsIgnoreCase(y)).isTrue()",
+ "assertThat(x).isEqualToIgnoringCase(y)"),
+ arguments("String", "assertThat(x.contains(y)).isTrue()", "assertThat(x).contains(y)"),
+ arguments(
+ "String", "assertThat(x.startsWith(y)).isTrue()", "assertThat(x).startsWith(y)"),
+ arguments("String", "assertThat(x.endsWith(y)).isTrue()", "assertThat(x).endsWith(y)"),
+ arguments("String", "assertThat(x.matches(y)).isTrue()", "assertThat(x).matches(y)"),
+ arguments("String", "assertThat(x.trim()).isEmpty()", "assertThat(x).isBlank()"),
+ arguments("String", "assertThat(x.length()).isEqualTo(5)", "assertThat(x).hasSize(5)"),
+// arguments("String", "assertThat(x).hasSize(y.length())", "assertThat(x).hasSameSizeAs(y)"),
+ // Related to File
+ arguments("java.io.File", "assertThat(x).hasSize(0)", "assertThat(x).isEmpty()"),
+ arguments("java.io.File", "assertThat(x.length()).isZero()", "assertThat(x).isEmpty()"),
+ arguments(
+ "java.io.File", "assertThat(x.length()).isEqualTo(3)", "assertThat(x).hasSize(3)"),
+ arguments("java.io.File", "assertThat(x.canRead()).isTrue()", "assertThat(x).canRead()"),
+ arguments(
+ "java.io.File", "assertThat(x.canWrite()).isTrue()", "assertThat(x).canWrite()"),
+ arguments("java.io.File", "assertThat(x.exists()).isTrue()", "assertThat(x).exists()"),
+ arguments(
+ "java.io.File",
+ "assertThat(x.getName()).isEqualTo(\"a\")",
+ "assertThat(x).hasName(\"a\")"),
+ arguments(
+ "java.io.File",
+ "assertThat(x.getParent()).isEqualTo(\"b\")",
+ "assertThat(x).hasParent(\"b\")"),
+ arguments(
+ "java.io.File",
+ "assertThat(x.getParentFile()).isNull()",
+ "assertThat(x).hasNoParent()"),
+ arguments(
+ "java.io.File", "assertThat(x.isAbsolute()).isTrue()", "assertThat(x).isAbsolute()"),
+ arguments(
+ "java.io.File", "assertThat(x.isAbsolute()).isFalse()", "assertThat(x).isRelative()"),
+ arguments(
+ "java.io.File",
+ "assertThat(x.isDirectory()).isTrue()",
+ "assertThat(x).isDirectory()"),
+ arguments("java.io.File", "assertThat(x.isFile()).isTrue()", "assertThat(x).isFile()"),
+ arguments(
+ "java.io.File", "assertThat(x.list()).isEmpty()", "assertThat(x).isEmptyDirectory()"),
+ // Related to Path
+ arguments(
+ "java.nio.file.Path",
+ "assertThat(x.startsWith(\"x\")).isTrue()",
+ "assertThat(x).startsWithRaw(Path.of(\"x\"))"),
+ arguments(
+ "java.nio.file.Path",
+ "assertThat(x.endsWith(\"y\")).isTrue()",
+ "assertThat(x).endsWithRaw(Path.of(\"y\"))"),
+ arguments(
+ "java.nio.file.Path",
+ "assertThat(x.getParent()).isEqualTo(y)",
+ "assertThat(x).hasParentRaw(y)"),
+ arguments(
+ "java.nio.file.Path",
+ "assertThat(x.getParent()).isNull()",
+ "assertThat(x).hasNoParentRaw()"),
+ arguments(
+ "java.nio.file.Path",
+ "assertThat(x.isAbsolute()).isTrue()",
+ "assertThat(x).isAbsolute()"),
+ arguments(
+ "java.nio.file.Path",
+ "assertThat(x.isAbsolute()).isFalse()",
+ "assertThat(x).isRelative()"),
+ // Related to Array
+// arguments("Object[]", "assertThat(x.length).isZero()", "assertThat(x).isEmpty()"),
+// arguments("String[]", "assertThat(x.length).isEqualTo(7)", "assertThat(x).hasSize(7)"),
+// arguments(
+// "int[]",
+// "assertThat(x.length).isEqualTo(y.length)",
+// "assertThat(x).hasSameSizeAs(y)"),
+// arguments(
+// "boolean[]",
+// "assertThat(x.length).isLessThanOrEqualTo(2)",
+// "assertThat(x).hasSizeLessThanOrEqualTo(2)"),
+// arguments(
+// "double[]", "assertThat(x.length).isLessThan(5)", "assertThat(x).hasSizeLessThan(5)"),
+// arguments(
+// "long[]",
+// "assertThat(x.length).isGreaterThan(4)",
+// "assertThat(x).hasSizeGreaterThan(4)"),
+// arguments(
+// "char[]",
+// "assertThat(x.length).isGreaterThanOrEqualTo(1)",
+// "assertThat(x).hasSizeGreaterThanOrEqualTo(1)"),
+ // Related to Collection
+ arguments(
+ "java.util.Collection",
+ "assertThat(x.isEmpty()).isTrue()",
+ "assertThat(x).isEmpty()"),
+ arguments(
+ "java.util.Collection",
+ "assertThat(x.size()).isZero()",
+ "assertThat(x).isEmpty()"),
+ arguments(
+ "java.util.Collection",
+ "assertThat(x.contains(\"f\")).isTrue()",
+ "assertThat(x).contains(\"f\")"),
+ arguments(
+ "java.util.Collection",
+ "assertThat(x.containsAll(y)).isTrue()",
+ "assertThat(x).containsAll(y)"),
+ // Related to Map
+// arguments(
+// "java.util.Map",
+// "assertThat(x).hasSize(y.size())",
+// "assertThat(x).hasSameSizeAs(y)"),
+ arguments(
+ "java.util.Map",
+ "assertThat(x.containsKey(\"b\")).isTrue()",
+ "assertThat(x).containsKey(\"b\")"),
+ arguments(
+ "java.util.Map",
+ "assertThat(x.keySet()).contains(\"b\")",
+ "assertThat(x).containsKey(\"b\")"),
+ arguments(
+ "java.util.Map",
+ "assertThat(x.keySet()).containsOnly(\"a\")",
+ "assertThat(x).containsOnlyKeys(\"a\")"),
+ arguments(
+ "java.util.Map",
+ "assertThat(x.containsValue(value)).isTrue()",
+ "assertThat(x).containsValue(value)"),
+ arguments(
+ "java.util.Map",
+ "assertThat(x.values()).contains(value)",
+ "assertThat(x).containsValue(value)"),
+ arguments(
+ "java.util.Map",
+ "assertThat(x.get(\"a\")).isEqualTo(value)",
+ "assertThat(x).containsEntry(\"a\", value)"),
+ // Related to Optional
+ arguments(
+ "java.util.Optional",
+ "assertThat(x.isPresent()).isTrue()",
+ "assertThat(x).isPresent()"),
+ arguments(
+ "java.util.Optional",
+ "assertThat(x.get()).isEqualTo(value)",
+ "assertThat(x).contains(value)"),
+ arguments(
+ "java.util.Optional",
+ "assertThat(x.get()).isSameAs(value)",
+ "assertThat(x).containsSame(value)"));
+ }
+
+ @ParameterizedTest
+ @MethodSource("replacements")
+ void sonarReplacements(
+ String argumentsType, String assertToReplace, String dedicatedAssertion) {
+ String template =
+ """
+ import %1$s;
+ import static org.assertj.core.api.Assertions.assertThat;
+
+ class A {
+ void test(%2$s x, %2$s y, Object value) {
+ %3$s;
+ }
+ }
+ """;
+ String imprt = argumentsType
+ .replaceAll("^([A-Z])", "java.lang.$1")
+ .replaceAll("<.*>", "");
+ rewriteRun(
+ java(
+ template.formatted(imprt, argumentsType, assertToReplace),
+ template.formatted(imprt, argumentsType, dedicatedAssertion)));
+ }
+ }
}
diff --git a/src/test/java/org/openrewrite/java/testing/assertj/IsEqualToBooleanTest.java b/src/test/java/org/openrewrite/java/testing/assertj/IsEqualToBooleanTest.java
deleted file mode 100644
index e00d2d055..000000000
--- a/src/test/java/org/openrewrite/java/testing/assertj/IsEqualToBooleanTest.java
+++ /dev/null
@@ -1,103 +0,0 @@
-/*
- * Copyright 2024 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * 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 org.junit.jupiter.api.Test;
-import org.openrewrite.DocumentExample;
-import org.openrewrite.InMemoryExecutionContext;
-import org.openrewrite.java.JavaParser;
-import org.openrewrite.test.RecipeSpec;
-import org.openrewrite.test.RewriteTest;
-
-import static org.openrewrite.java.Assertions.java;
-
-class IsEqualToBooleanTest implements RewriteTest {
-
- @Override
- public void defaults(RecipeSpec spec) {
- spec
- .parser(JavaParser.fromJavaVersion().classpathFromResources(new InMemoryExecutionContext(), "assertj-core-3.24"))
- .recipe(new IsEqualToBoolean());
- }
-
- @DocumentExample
- @Test
- void convertsIsEqualToTrue() {
- rewriteRun(
- // language=java
- java(
- """
- import static org.assertj.core.api.Assertions.assertThat;
- class Test {
- void test() {
- assertThat(true).isEqualTo(true);
- }
- }
- """,
- """
- import static org.assertj.core.api.Assertions.assertThat;
- class Test {
- void test() {
- assertThat(true).isTrue();
- }
- }
- """
- )
- );
- }
-
- @Test
- void convertsIsEqualToFalse() {
- rewriteRun(
- // language=java
- java(
- """
- import static org.assertj.core.api.Assertions.assertThat;
- class Test {
- void test() {
- assertThat(false).isEqualTo(false);
- }
- }
- """,
- """
- import static org.assertj.core.api.Assertions.assertThat;
- class Test {
- void test() {
- assertThat(false).isFalse();
- }
- }
- """
- )
- );
- }
-
- @Test
- void noChangeOnVariable() {
- rewriteRun(
- // language=java
- java(
- """
- import static org.assertj.core.api.Assertions.assertThat;
- class Test {
- void test(boolean b) {
- assertThat(false).isEqualTo(b);
- }
- }
- """
- )
- );
- }
-}
diff --git a/src/test/java/org/openrewrite/java/testing/assertj/IsEqualToEmptyStringTest.java b/src/test/java/org/openrewrite/java/testing/assertj/IsEqualToEmptyStringTest.java
deleted file mode 100644
index 61a41413e..000000000
--- a/src/test/java/org/openrewrite/java/testing/assertj/IsEqualToEmptyStringTest.java
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * Copyright 2024 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * 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 org.junit.jupiter.api.Test;
-import org.openrewrite.DocumentExample;
-import org.openrewrite.InMemoryExecutionContext;
-import org.openrewrite.java.JavaParser;
-import org.openrewrite.test.RecipeSpec;
-import org.openrewrite.test.RewriteTest;
-
-import static org.openrewrite.java.Assertions.java;
-
-class IsEqualToEmptyStringTest implements RewriteTest {
-
- @Override
- public void defaults(RecipeSpec spec) {
- spec
- .parser(JavaParser.fromJavaVersion().classpathFromResources(new InMemoryExecutionContext(), "assertj-core-3.24"))
- .recipe(new IsEqualToEmptyString());
- }
-
- @DocumentExample
- @Test
- void convertsIsEqualToEmptyString() {
- rewriteRun(
- // language=java
- java(
- """
- import static org.assertj.core.api.Assertions.assertThat;
- class Test {
- void test() {
- assertThat("test").isEqualTo("");
- }
- }
- """,
- """
- import static org.assertj.core.api.Assertions.assertThat;
- class Test {
- void test() {
- assertThat("test").isEmpty();
- }
- }
- """
- )
- );
- }
-}
diff --git a/src/test/java/org/openrewrite/java/testing/assertj/SimplifyAssertJAssertionTest.java b/src/test/java/org/openrewrite/java/testing/assertj/SimplifyAssertJAssertionTest.java
new file mode 100644
index 000000000..32ddb3b93
--- /dev/null
+++ b/src/test/java/org/openrewrite/java/testing/assertj/SimplifyAssertJAssertionTest.java
@@ -0,0 +1,166 @@
+/*
+ * Copyright 2023 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * 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 org.junit.jupiter.api.Test;
+import org.openrewrite.DocumentExample;
+import org.openrewrite.InMemoryExecutionContext;
+import org.openrewrite.java.JavaParser;
+import org.openrewrite.test.RecipeSpec;
+import org.openrewrite.test.RewriteTest;
+
+import static org.openrewrite.java.Assertions.java;
+
+class SimplifyAssertJAssertionTest implements RewriteTest {
+ @Override
+ public void defaults(RecipeSpec spec) {
+ spec.parser(JavaParser.fromJavaVersion().classpathFromResources(new InMemoryExecutionContext(), "assertj-core-3.24"));
+ }
+
+ @Test
+ void primitiveBooleanIsFalse() {
+ rewriteRun(
+ spec -> spec.recipe(new SimplifyAssertJAssertion("isEqualTo", "false", "isFalse", "boolean")),
+ //language=java
+ java(
+ """
+ import static org.assertj.core.api.Assertions.assertThat;
+ class Test {
+ void test() {
+ assertThat(false).isEqualTo(false);
+ }
+ }
+ """,
+ """
+ import static org.assertj.core.api.Assertions.assertThat;
+ class Test {
+ void test() {
+ assertThat(false).isFalse();
+ }
+ }
+ """
+ )
+ );
+ }
+
+ @Test
+ void objectBooleanIsFalse() {
+ rewriteRun(
+ spec -> spec.recipe(new SimplifyAssertJAssertion("isEqualTo", "false", "isFalse", "java.lang.Boolean")),
+ //language=java
+ java(
+ """
+ import static org.assertj.core.api.Assertions.assertThat;
+ class Test {
+ void test(Boolean arg) {
+ assertThat(arg).isEqualTo(false);
+ }
+ }
+ """,
+ """
+ import static org.assertj.core.api.Assertions.assertThat;
+ class Test {
+ void test(Boolean arg) {
+ assertThat(arg).isFalse();
+ }
+ }
+ """
+ )
+ );
+ }
+
+
+ @DocumentExample
+ @Test
+ void convertsStringIsEqualToNull() {
+ rewriteRun(
+ spec -> spec.recipe(new SimplifyAssertJAssertion("isEqualTo", "null", "isNull", "java.lang.Object")),
+ // language=java
+ java(
+ """
+ import static org.assertj.core.api.Assertions.assertThat;
+ class Test {
+ void test(String a) {
+ assertThat(a).isEqualTo(null);
+ }
+ }
+ """,
+ """
+ import static org.assertj.core.api.Assertions.assertThat;
+ class Test {
+ void test(String a) {
+ assertThat(a).isNull();
+ }
+ }
+ """
+ )
+ );
+ }
+
+ @Test
+ void convertsObjectIsEqualToNull() {
+ rewriteRun(
+ spec -> spec.recipe(new SimplifyAssertJAssertion("isEqualTo", "null", "isNull", "java.lang.Object")),
+ // language=java
+ java(
+ """
+ import static org.assertj.core.api.Assertions.assertThat;
+ class Test {
+ void test(Object o) {
+ assertThat(o).isEqualTo(null);
+ }
+ }
+ """,
+ """
+ import static org.assertj.core.api.Assertions.assertThat;
+ class Test {
+ void test(Object o) {
+ assertThat(o).isNull();
+ }
+ }
+ """
+ )
+ );
+ }
+
+
+ @Test
+ void convertsIsEqualToEmptyString() {
+ rewriteRun(
+ spec -> spec.recipe(new SimplifyAssertJAssertion("isEqualTo", "\"\"", "isEmpty", "java.lang.String")),
+ // language=java
+ java(
+ """
+ import static org.assertj.core.api.Assertions.assertThat;
+ class Test {
+ void test() {
+ assertThat("test").isEqualTo("");
+ }
+ }
+ """,
+ """
+ import static org.assertj.core.api.Assertions.assertThat;
+ class Test {
+ void test() {
+ assertThat("test").isEmpty();
+ }
+ }
+ """
+ )
+ );
+ }
+
+}
diff --git a/src/test/java/org/openrewrite/java/testing/assertj/SimplifyChainedAssertJAssertionTest.java b/src/test/java/org/openrewrite/java/testing/assertj/SimplifyChainedAssertJAssertionTest.java
index f50cd45f5..8ed5669a3 100644
--- a/src/test/java/org/openrewrite/java/testing/assertj/SimplifyChainedAssertJAssertionTest.java
+++ b/src/test/java/org/openrewrite/java/testing/assertj/SimplifyChainedAssertJAssertionTest.java
@@ -16,6 +16,7 @@
package org.openrewrite.java.testing.assertj;
import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.openrewrite.DocumentExample;
import org.openrewrite.InMemoryExecutionContext;
@@ -30,8 +31,7 @@ class SimplifyChainedAssertJAssertionTest implements RewriteTest {
@Override
public void defaults(RecipeSpec spec) {
spec
- .parser(JavaParser.fromJavaVersion().classpathFromResources(new InMemoryExecutionContext(),
- "junit-jupiter-api-5.9", "assertj-core-3.24"));
+ .parser(JavaParser.fromJavaVersion().classpathFromResources(new InMemoryExecutionContext(), "assertj-core-3.24"));
}
@DocumentExample
@@ -42,24 +42,18 @@ void stringIsEmpty() {
//language=java
java(
"""
- import org.junit.jupiter.api.Test;
-
import static org.assertj.core.api.Assertions.assertThat;
-
+
class MyTest {
- @Test
void testMethod() {
assertThat("hello world".isEmpty()).isTrue();
}
}
""",
"""
- import org.junit.jupiter.api.Test;
-
import static org.assertj.core.api.Assertions.assertThat;
-
+
class MyTest {
- @Test
void testMethod() {
assertThat("hello world").isEmpty();
}
@@ -76,18 +70,18 @@ void stringIsEmptyDescribedAs() {
spec -> spec.recipe(new SimplifyChainedAssertJAssertion("isEmpty", "isTrue", "isEmpty", "java.lang.String")),
//language=java
java(
- """
+ """
import static org.assertj.core.api.Assertions.assertThat;
-
+
class MyTest {
void testMethod(String actual) {
assertThat(actual.isEmpty()).as("Reason").isTrue();
}
}
""",
- """
+ """
import static org.assertj.core.api.Assertions.assertThat;
-
+
class MyTest {
void testMethod(String actual) {
assertThat(actual).as("Reason").isEmpty();
@@ -108,32 +102,26 @@ void chainedRecipes() {
//language=java
java(
"""
- import org.junit.jupiter.api.Test;
-
import static org.assertj.core.api.Assertions.assertThat;
-
+
class MyTest {
- @Test
void testMethod() {
assertThat(getString().isEmpty()).isTrue();
}
-
+
String getString() {
return "hello world";
}
}
""",
"""
- import org.junit.jupiter.api.Test;
-
import static org.assertj.core.api.Assertions.assertThat;
-
+
class MyTest {
- @Test
void testMethod() {
assertThat(getString()).isEmpty();
}
-
+
String getString() {
return "hello world";
}
@@ -153,38 +141,30 @@ void chainedRecipesOfDifferingTypes() {
//language=java
java(
"""
- import org.junit.jupiter.api.Test;
-
import java.nio.file.Path;
-
+
import static org.assertj.core.api.Assertions.assertThat;
-
+
class MyTest {
- @Test
void string(String actual) {
assertThat(actual.startsWith("prefix")).isTrue();
}
- @Test
void path(Path actual) {
assertThat(actual.startsWith("prefix")).isTrue();
}
}
""",
"""
- import org.junit.jupiter.api.Test;
-
import java.nio.file.Path;
import static org.assertj.core.api.Assertions.assertThat;
class MyTest {
- @Test
void string(String actual) {
assertThat(actual).startsWith("prefix");
}
- @Test
void path(Path actual) {
assertThat(actual).startsWithRaw(Path.of("prefix"));
}
@@ -201,34 +181,28 @@ void assertThatArgHasArgument() {
//language=java
java(
"""
- import org.junit.jupiter.api.Test;
-
import static org.assertj.core.api.Assertions.assertThat;
-
+
class MyTest {
- @Test
void testMethod() {
String expected = "hello world";
assertThat(getString().equalsIgnoreCase(expected)).isTrue();
}
-
+
String getString() {
return "hello world";
}
}
""",
"""
- import org.junit.jupiter.api.Test;
-
import static org.assertj.core.api.Assertions.assertThat;
-
+
class MyTest {
- @Test
void testMethod() {
String expected = "hello world";
assertThat(getString()).isEqualToIgnoringCase(expected);
}
-
+
String getString() {
return "hello world";
}
@@ -245,34 +219,28 @@ void replacementHasArgument() {
//language=java
java(
"""
- import org.junit.jupiter.api.Test;
-
import static org.assertj.core.api.Assertions.assertThat;
-
+
class MyTest {
- @Test
void testMethod() {
int length = 5;
assertThat(getString().length()).isEqualTo(length);
}
-
+
String getString() {
return "hello world";
}
}
""",
"""
- import org.junit.jupiter.api.Test;
-
import static org.assertj.core.api.Assertions.assertThat;
-
+
class MyTest {
- @Test
void testMethod() {
int length = 5;
assertThat(getString()).hasSize(length);
}
-
+
String getString() {
return "hello world";
}
@@ -290,32 +258,26 @@ void normalCase() {
//language=java
java(
"""
- import org.junit.jupiter.api.Test;
-
import static org.assertj.core.api.Assertions.assertThat;
-
+
class MyTest {
- @Test
void testMethod() {
assertThat(getString().trim()).isEmpty();
}
-
+
String getString() {
return "hello world";
}
}
""",
"""
- import org.junit.jupiter.api.Test;
-
import static org.assertj.core.api.Assertions.assertThat;
-
+
class MyTest {
- @Test
void testMethod() {
assertThat(getString()).isBlank();
}
-
+
String getString() {
return "hello world";
}
@@ -335,12 +297,9 @@ void stringContains() {
//language=java
java(
"""
- import org.junit.jupiter.api.Test;
-
import static org.assertj.core.api.Assertions.assertThat;
-
+
class MyTest {
- @Test
void testMethod() {
assertThat("hello world".contains("lo wo")).isTrue();
assertThat("hello world".contains("lll")).isFalse();
@@ -348,12 +307,9 @@ void testMethod() {
}
""",
"""
- import org.junit.jupiter.api.Test;
-
import static org.assertj.core.api.Assertions.assertThat;
-
+
class MyTest {
- @Test
void testMethod() {
assertThat("hello world").contains("lo wo");
assertThat("hello world").doesNotContain("lll");
@@ -372,40 +328,36 @@ void mapMethodDealsWithTwoArguments() {
//language=java
java(
"""
- import org.junit.jupiter.api.Test;
import java.util.Collections;
import java.util.Map;
-
+
import static org.assertj.core.api.Assertions.assertThat;
-
+
class MyTest {
- @Test
void testMethod() {
String key = "key";
String value = "value";
assertThat(getMap().get(key)).isEqualTo(value);
}
-
+
Map getMap() {
return Collections.emptyMap();
}
}
""",
"""
- import org.junit.jupiter.api.Test;
import java.util.Collections;
import java.util.Map;
-
+
import static org.assertj.core.api.Assertions.assertThat;
-
+
class MyTest {
- @Test
void testMethod() {
String key = "key";
String value = "value";
assertThat(getMap()).containsEntry(key, value);
}
-
+
Map getMap() {
return Collections.emptyMap();
}
@@ -422,32 +374,26 @@ void isNotEmptyTest() {
//language=java
java(
"""
- import org.junit.jupiter.api.Test;
-
import static org.assertj.core.api.Assertions.assertThat;
-
+
class MyTest {
- @Test
void testMethod() {
assertThat(getString().isEmpty()).isFalse();
}
-
+
String getString() {
return "hello world";
}
}
""",
"""
- import org.junit.jupiter.api.Test;
-
import static org.assertj.core.api.Assertions.assertThat;
-
+
class MyTest {
- @Test
void testMethod() {
assertThat(getString()).isNotEmpty();
}
-
+
String getString() {
return "hello world";
}
@@ -464,16 +410,13 @@ void doesNoRunOnWrongCombination() {
//language=java
java(
"""
- import org.junit.jupiter.api.Test;
-
import static org.assertj.core.api.Assertions.assertThat;
-
+
class MyTest {
- @Test
void testMethod() {
assertThat(getString().isBlank()).isFalse();
}
-
+
String getString() {
return "hello world";
}
@@ -483,42 +426,83 @@ String getString() {
);
}
- @Test
- @Issue("https://github.com/openrewrite/rewrite-testing-frameworks/issues/398")
- void sizeIsEqualToZeroToIsEmpty() {
- rewriteRun(
- spec -> spec.recipe(new SimplifyChainedAssertJAssertion("size", "isEqualTo", "hasSize", "java.util.List")),
- //language=java
- java(
- """
- import org.junit.jupiter.api.Test;
- import java.util.List;
-
- import static org.assertj.core.api.Assertions.assertThat;
-
- class MyTest {
- @Test
- void testMethod() {
- List objectIdentifies = List.of();
- assertThat(objectIdentifies.size()).isEqualTo(0);
- }
- }
- """,
- """
- import org.junit.jupiter.api.Test;
- import java.util.List;
-
- import static org.assertj.core.api.Assertions.assertThat;
-
- class MyTest {
- @Test
- void testMethod() {
- List objectIdentifies = List.of();
- assertThat(objectIdentifies).isEmpty();
- }
- }
- """
- )
- );
+ @Nested
+ class OptionalAssertions {
+
+ @Test
+ void simplifyPresenceAssertion() {
+ rewriteRun(
+ spec -> spec.recipes(
+ new SimplifyChainedAssertJAssertion("isPresent", "isTrue", "isPresent", "java.util.Optional"),
+ new SimplifyChainedAssertJAssertion("isEmpty", "isTrue", "isEmpty", "java.util.Optional"),
+ new SimplifyChainedAssertJAssertion("isPresent", "isFalse", "isNotPresent", "java.util.Optional"),
+ new SimplifyChainedAssertJAssertion("isEmpty", "isFalse", "isNotEmpty", "java.util.Optional")
+ ),
+ //language=java
+ java(
+ """
+ import static org.assertj.core.api.Assertions.assertThat;
+ import java.util.Optional;
+
+ class Test {
+ void simpleTest(Optional o) {
+ assertThat(o.isPresent()).isTrue();
+ assertThat(o.isEmpty()).isTrue();
+ assertThat(o.isPresent()).isFalse();
+ assertThat(o.isEmpty()).isFalse();
+ }
+ }
+ """,
+ """
+ import static org.assertj.core.api.Assertions.assertThat;
+ import java.util.Optional;
+
+ class Test {
+ void simpleTest(Optional o) {
+ assertThat(o).isPresent();
+ assertThat(o).isEmpty();
+ assertThat(o).isNotPresent();
+ assertThat(o).isNotEmpty();
+ }
+ }
+ """
+ )
+ );
+ }
+
+ @Test
+ void simplifiyEqualityAssertion() {
+ rewriteRun(
+ spec -> spec.recipes(
+ new SimplifyChainedAssertJAssertion("get", "isEqualTo", "contains", "java.util.Optional"),
+ new SimplifyChainedAssertJAssertion("get", "isSameAs", "containsSame", "java.util.Optional")
+ ),
+ //language=java
+ java(
+ """
+ import static org.assertj.core.api.Assertions.assertThat;
+ import java.util.Optional;
+
+ class Test {
+ void simpleTest(Optional o) {
+ assertThat(o.get()).isEqualTo("foo");
+ assertThat(o.get()).isSameAs("foo");
+ }
+ }
+ """,
+ """
+ import static org.assertj.core.api.Assertions.assertThat;
+ import java.util.Optional;
+
+ class Test {
+ void simpleTest(Optional o) {
+ assertThat(o).contains("foo");
+ assertThat(o).containsSame("foo");
+ }
+ }
+ """
+ )
+ );
+ }
}
}
diff --git a/src/test/java/org/openrewrite/java/testing/assertj/SimplifyChainedAssertJAssertionWithOptionalTest.java b/src/test/java/org/openrewrite/java/testing/assertj/SimplifyChainedAssertJAssertionWithOptionalTest.java
deleted file mode 100644
index 8b515a371..000000000
--- a/src/test/java/org/openrewrite/java/testing/assertj/SimplifyChainedAssertJAssertionWithOptionalTest.java
+++ /dev/null
@@ -1,129 +0,0 @@
-/*
- * Copyright 2024 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * 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 org.junit.jupiter.api.Test;
-import org.openrewrite.DocumentExample;
-import org.openrewrite.InMemoryExecutionContext;
-import org.openrewrite.java.JavaParser;
-import org.openrewrite.test.RecipeSpec;
-import org.openrewrite.test.RewriteTest;
-
-import static org.openrewrite.java.Assertions.java;
-
-class SimplifyChainedAssertJAssertionWithOptionalTest implements RewriteTest {
- @Override
- public void defaults(RecipeSpec spec) {
- spec
- .parser(JavaParser.fromJavaVersion().classpathFromResources(new InMemoryExecutionContext(),
- "junit-jupiter-api-5.9", "assertj-core-3.24"));
- }
-
-
- @DocumentExample
- @Test
- void simplifyPresenceAssertion() {
- rewriteRun(
- spec -> spec.recipes(
- new SimplifyChainedAssertJAssertion("isPresent", "isTrue", "isPresent", "java.util.Optional"),
- new SimplifyChainedAssertJAssertion("isEmpty", "isTrue", "isEmpty", "java.util.Optional"),
- new SimplifyChainedAssertJAssertion("isPresent", "isFalse", "isNotPresent", "java.util.Optional"),
- new SimplifyChainedAssertJAssertion("isEmpty", "isFalse", "isNotEmpty", "java.util.Optional")
- ),
- //language=java
- java(
- """
- import static org.assertj.core.api.Assertions.assertThat;
- import java.util.Optional;
- import org.junit.jupiter.api.Test;
-
- class Test {
-
- @Test
- void simpleTest() {
- Optional o = Optional.empty();
- assertThat(o.isPresent()).isTrue();
- assertThat(o.isEmpty()).isTrue();
- assertThat(o.isPresent()).isFalse();
- assertThat(o.isEmpty()).isFalse();
- }
- }
- """,
- """
- import static org.assertj.core.api.Assertions.assertThat;
- import java.util.Optional;
- import org.junit.jupiter.api.Test;
-
- class Test {
-
- @Test
- void simpleTest() {
- Optional o = Optional.empty();
- assertThat(o).isPresent();
- assertThat(o).isEmpty();
- assertThat(o).isNotPresent();
- assertThat(o).isNotEmpty();
- }
- }
- """
- )
- );
- }
-
- @Test
- void simplifiyEqualityAssertion() {
- rewriteRun(
- spec -> spec.recipes(
- new SimplifyChainedAssertJAssertion("get", "isEqualTo", "contains", "java.util.Optional"),
- new SimplifyChainedAssertJAssertion("get", "isSameAs", "containsSame", "java.util.Optional")
- ),
- //language=java
- java(
- """
- import static org.assertj.core.api.Assertions.assertThat;
- import java.util.Optional;
- import org.junit.jupiter.api.Test;
-
- class Test {
-
- @Test
- void simpleTest() {
- Optional o = Optional.empty();
- assertThat(o.get()).isEqualTo("foo");
- assertThat(o.get()).isSameAs("foo");
- }
- }
- """,
- """
- import static org.assertj.core.api.Assertions.assertThat;
- import java.util.Optional;
- import org.junit.jupiter.api.Test;
-
- class Test {
-
- @Test
- void simpleTest() {
- Optional o = Optional.empty();
- assertThat(o).contains("foo");
- assertThat(o).containsSame("foo");
- }
- }
- """
- )
- );
- }
-
-}
diff --git a/src/test/java/org/openrewrite/java/testing/assertj/MigrateChainedAssertToAssertJTest.java b/src/test/java/org/openrewrite/java/testing/assertj/SimplifyChainedAssertJAssertionsTest.java
similarity index 94%
rename from src/test/java/org/openrewrite/java/testing/assertj/MigrateChainedAssertToAssertJTest.java
rename to src/test/java/org/openrewrite/java/testing/assertj/SimplifyChainedAssertJAssertionsTest.java
index 51d071685..874d6480b 100644
--- a/src/test/java/org/openrewrite/java/testing/assertj/MigrateChainedAssertToAssertJTest.java
+++ b/src/test/java/org/openrewrite/java/testing/assertj/SimplifyChainedAssertJAssertionsTest.java
@@ -34,14 +34,12 @@
import static org.openrewrite.java.Assertions.java;
-class MigrateChainedAssertToAssertJTest implements RewriteTest {
+class SimplifyChainedAssertJAssertionsTest implements RewriteTest {
@Override
public void defaults(RecipeSpec spec) {
spec
.parser(JavaParser.fromJavaVersion()
- .classpathFromResources(new InMemoryExecutionContext(),
- "junit-jupiter-api-5.9",
- "assertj-core-3.24"))
+ .classpathFromResources(new InMemoryExecutionContext(), "assertj-core-3.24"))
.recipe(Environment.builder()
.scanRuntimeClasspath("org.openrewrite.java.testing.assertj")
.build()
@@ -57,25 +55,19 @@ void stringIsEmptyExample() {
//language=java
java(
"""
- import org.junit.jupiter.api.Test;
-
import static org.assertj.core.api.Assertions.assertThat;
class MyTest {
- @Test
void testMethod() {
String s = "hello world";
assertThat(s.isEmpty()).isTrue();
}
}
""",
- """
- import org.junit.jupiter.api.Test;
-
+ """
import static org.assertj.core.api.Assertions.assertThat;
class MyTest {
- @Test
void testMethod() {
String s = "hello world";
assertThat(s).isEmpty();
@@ -106,12 +98,10 @@ private static Stream stringReplacements() {
void stringReplacements(String chainedAssertion, String assertToReplace, String dedicatedAssertion, String firstArg, String secondArg) {
//language=java
String template = """
- import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
class MyTest {
- @Test
void test() {
int length = 5;
String expected = "hello world";
@@ -161,13 +151,11 @@ private static Stream fileReplacements() {
void fileReplacements(String chainedAssertion, String assertToReplace, String dedicatedAssertion, String firstArg, String secondArg) {
//language=java
String template = """
- import org.junit.jupiter.api.Test;
import java.io.File;
import static org.assertj.core.api.Assertions.assertThat;
class MyTest {
- @Test
void test() {
int length = 5;
String name = "hello world";
@@ -209,14 +197,12 @@ private static Stream pathReplacements() {
void pathReplacements(String chainedAssertion, String assertToReplace, String dedicatedAssertion, String firstArg, String secondArg) {
//language=java
String template = """
- import org.junit.jupiter.api.Test;
import java.nio.file.Path;
import java.nio.file.Paths;
import static org.assertj.core.api.Assertions.assertThat;
class MyTest {
- @Test
void test() {
Path path = Paths.get("");
%s
@@ -302,14 +288,12 @@ private static Stream mapReplacements() {
void mapReplacements(String chainedAssertion, String assertToReplace, String dedicatedAssertion, String firstArg, String secondArg) {
//language=java
String template = """
- import org.junit.jupiter.api.Test;
import java.util.Collections;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
class MyTest {
- @Test
void test() {
Map otherMap = Collections.emptyMap();
String key = "key";
@@ -343,13 +327,11 @@ void mapHasSameSizeAs() {
//language=java
java(
"""
- import org.junit.jupiter.api.Test;
import java.util.Map;
-
+
import static org.assertj.core.api.Assertions.assertThat;
class MyTest {
- @Test
void testMethod() {
Map mapA = Map.of();
Map mapB = Map.of();
@@ -358,13 +340,11 @@ void testMethod() {
}
""",
"""
- import org.junit.jupiter.api.Test;
import java.util.Map;
-
+
import static org.assertj.core.api.Assertions.assertThat;
class MyTest {
- @Test
void testMethod() {
Map mapA = Map.of();
Map mapB = Map.of();
@@ -392,13 +372,11 @@ private static Stream optionalReplacements() {
void optionalReplacements(String chainedAssertion, String assertToReplace, String dedicatedAssertion, String arg) {
//language=java
String template = """
- import org.junit.jupiter.api.Test;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
class MyTest {
- @Test
void test() {
String something = "hello world";
Optional helloWorld = Optional.of("hello world");
@@ -455,7 +433,7 @@ void test(Iterator iterator, Iterator otherIterator) {
);
}
}
-
+
@Nested
class Objects {
@Test
@@ -464,8 +442,6 @@ void objectoToStringReplacement() {
//language=java
java(
"""
- import org.junit.jupiter.api.Test;
-
import static org.assertj.core.api.Assertions.assertThat;
class MyTest {
@@ -475,9 +451,7 @@ void testMethod(Object argument) {
}
}
""",
- """
- import org.junit.jupiter.api.Test;
-
+ """
import static org.assertj.core.api.Assertions.assertThat;
class MyTest {