Skip to content

Commit

Permalink
Only add hamcrest-junit dependency when using assertThat or `assu…
Browse files Browse the repository at this point in the history
…meThat` (#577)

* remove hamcrest-junit dependency when migrating from JUnit 4 to 5

* Only add Hamcrest JUnit dependency when assertThat or assumeThat is used

* Create scanner visitors once

* Also create scanner visitor once

* Add missing trailing newline

* No need to scan for AddDependency

* Move recipe to fix reference from junit5.yml

---------

Co-authored-by: Tim te Beek <[email protected]>
  • Loading branch information
FieteO and timtebeek authored Aug 17, 2024
1 parent da544f8 commit b885d12
Show file tree
Hide file tree
Showing 3 changed files with 222 additions and 7 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
/*
* Copyright 2024 the original author or authors.
* <p>
* 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
* <p>
* https://www.apache.org/licenses/LICENSE-2.0
* <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.junit5;

import org.openrewrite.ExecutionContext;
import org.openrewrite.ScanningRecipe;
import org.openrewrite.Tree;
import org.openrewrite.TreeVisitor;
import org.openrewrite.java.MethodMatcher;
import org.openrewrite.java.dependencies.AddDependency;
import org.openrewrite.java.tree.JavaSourceFile;
import org.openrewrite.java.tree.JavaType;

import java.util.concurrent.atomic.AtomicBoolean;

public class AddHamcrestJUnitDependency extends ScanningRecipe<AtomicBoolean> {

@Override
public String getDisplayName() {
return "Add Hamcrest JUnit dependency";
}

@Override
public String getDescription() {
return "Add Hamcrest JUnit dependency only if JUnit 4's `assertThat` or `assumeThat` is used.";
}

@Override
public AtomicBoolean getInitialValue(ExecutionContext ctx) {
return new AtomicBoolean(false);
}

@Override
public TreeVisitor<?, ExecutionContext> getScanner(AtomicBoolean acc) {
// No need to scan for AddDependency, as we'll unconditionally add the dependency if we find a match below
MethodMatcher methodMatcher = new MethodMatcher("org.junit.Ass* *That(..)");
return new TreeVisitor<Tree, ExecutionContext>() {
@Override
public Tree preVisit(Tree tree, ExecutionContext ctx) {
stopAfterPreVisit();
if (tree instanceof JavaSourceFile && !acc.get()) {
for (JavaType.Method type : ((JavaSourceFile) tree).getTypesInUse().getUsedMethods()) {
if (methodMatcher.matches(type)) {
acc.set(true);
}
}
}
return tree;
}
};
}

@Override
public TreeVisitor<?, ExecutionContext> getVisitor(AtomicBoolean acc) {
if (acc.get()) {
// We can unconditionally add the dependency here
return new AddDependency(
"org.hamcrest",
"hamcrest-junit",
"2.x",
null,
null,
null,
null,
null,
null,
"test",
null,
null,
null,
true
).getVisitor();
}
return TreeVisitor.noop();
}
}
8 changes: 1 addition & 7 deletions src/main/resources/META-INF/rewrite/junit5.yml
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ recipeList:
groupId: org.apache.maven.surefire
artifactId: surefire-junit*
- org.openrewrite.java.testing.junit5.UpgradeSurefirePlugin
- org.openrewrite.java.testing.junit5.AddHamcrestJUnitDependency
- org.openrewrite.java.testing.junit5.UseHamcrestAssertThat
- org.openrewrite.java.testing.junit5.MigrateAssumptions
- org.openrewrite.java.testing.junit5.UseMockitoExtension
Expand Down Expand Up @@ -160,13 +161,6 @@ tags:
- junit
- hamcrest
recipeList:
- org.openrewrite.java.dependencies.AddDependency:
groupId: org.hamcrest
artifactId: hamcrest-junit
version: 2.x
scope: test
onlyIfUsing: org.junit.Assume
acceptTransitive: true
- org.openrewrite.java.ChangeMethodTargetToStatic:
methodPattern: org.junit.Assume assumeThat(..)
fullyQualifiedTargetTypeName: org.hamcrest.junit.MatcherAssume
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
/*
* Copyright 2024 the original author or authors.
* <p>
* 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
* <p>
* https://www.apache.org/licenses/LICENSE-2.0
* <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.junit5;

import org.intellij.lang.annotations.Language;
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;
import static org.openrewrite.maven.Assertions.pomXml;

class AddHamcrestJUnitDependencyTest implements RewriteTest {

@Language("xml")
private static final String POM_BEFORE = """
<project>
<groupId>org.example</groupId>
<artifactId>project</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
""";

@Language("xml")
private static final String POM_AFTER = """
<project>
<groupId>org.example</groupId>
<artifactId>project</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-junit</artifactId>
<version>2.0.0.0</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
""";

@Override
public void defaults(RecipeSpec spec) {
spec.recipe(new AddHamcrestJUnitDependency())
.parser(JavaParser.fromJavaVersion().classpathFromResources(new InMemoryExecutionContext(),
"hamcrest",
"junit-4"));

}

@Test
@DocumentExample
void shouldAddWhenUsingAssertThat() {
rewriteRun(
//language=java
java(
"""
class FooTest {
void bar() {
org.junit.Assert.assertThat("a", org.hamcrest.Matchers.is("a"));
}
}
"""
),
pomXml(POM_BEFORE, POM_AFTER)
);
}

@Test
void shouldAddWhenUsingAssumeThat() {
rewriteRun(
//language=java
java(
"""
class FooTest {
void bar() {
org.junit.Assume.assumeThat("a", org.hamcrest.Matchers.is("a"));
}
}
"""
),
pomXml(POM_BEFORE, POM_AFTER)
);
}

@Test
void shouldNotAddWhenUsingAssertTrue() {
rewriteRun(
//language=java
java(
"""
class FooTest {
void bar() {
org.junit.Assume.assumeTrue(true);
org.junit.Assert.assertTrue(true);
}
}
"""
),
pomXml(POM_BEFORE)
);
}
}

0 comments on commit b885d12

Please sign in to comment.