OpenRewrite Recipe Development
This skill provides guidelines for developing OpenRewrite recipes and maintaining their tests, with a focus on import ordering issues.
Fixing Import Ordering Test Failures
🔧 OpenRewrite recipe tests often fail due to import order differences, not actual transformation issues.
Problem
OpenRewrite recipe tests fail with diffs showing only import order differences:
-import java.util.List;
-import org.assertj.core.api.Assertions;
+import org.assertj.core.api.Assertions;
+import java.util.List;
Root Cause
OpenRewrite manages imports automatically based on:
- Existing imports in the file
- JavaTemplate configuration
- Import optimization rules
- The order may differ from test expectations
Solution Approach
1. Fix the Recipe (if imports are missing)
Ensure your JavaTemplate is properly configured:
JavaTemplate template = JavaTemplate
.builder("Your.template.code()")
.imports(
"org.assertj.core.api.Assertions",
"org.eclipse.collections.impl.utility.Iterate"
)
.contextSensitive() // Important for proper context handling
.javaParser(JavaParser.fromJavaVersion()
.classpath("assertj-core", "eclipse-collections", "eclipse-collections-api")
)
.build();
Don't forget to call:
maybeAddImport("org.assertj.core.api.Assertions");
maybeAddImport("org.eclipse.collections.impl.utility.Iterate");
maybeRemoveImport("old.package.OldClass");
2. Fix the Test Expectations
Accept the actual import order that OpenRewrite produces:
❌ Instead of forcing a specific order:
// DON'T expect a specific order you want
"import java.util.List;\n" +
"import org.assertj.core.api.Assertions;\n"
✅ Use the actual order OpenRewrite produces:
// DO accept the order OpenRewrite generates
"import org.assertj.core.api.Assertions;\n" +
"import org.eclipse.collections.impl.utility.Iterate;\n" +
"\n" +
"import java.util.List;\n"
3. Common Import Ordering Patterns
OpenRewrite typically orders imports as:
- Third-party packages (org.assertj, org.eclipse.collections, etc.)
- Blank line
- Java standard library (
java.*,javax.*) - Blank line (if static imports exist)
- Static imports
Quick Fix Steps
- Run the failing test and copy the actual output from the error message
- Replace the expected output in your test with the actual output
- Verify the transformation logic is correct (ignore import order)
- Re-run the test to confirm it passes
Note on ~~> Syntax
The ~~> prefix in test expectations is not standard in all codebases. It's used in some OpenRewrite projects to indicate "ignore everything before this line" but isn't recognized in all contexts. If you see it failing, remove it and use exact matching instead.
Example Fix
@Test
void replacesVerifyWithAssertJ() {
rewriteRun(
java(
// Input
"""
import org.eclipse.collections.impl.test.Verify;
import java.util.List;
class Test {
void test() {
List<String> list = List.of("a", "b", "c");
Verify.assertCount(2, list, each -> each.length() > 0);
}
}
""",
// Expected output - use actual order from test failure
"""
import org.assertj.core.api.Assertions;
import org.eclipse.collections.impl.utility.Iterate;
import java.util.List;
class Test {
void test() {
List<String> list = List.of("a", "b", "c");
Assertions.assertThat(Iterate.count(list, each -> each.length() > 0)).isEqualTo(2);
}
}
"""
)
);
}
Testing Best Practices
Type Validation in Tests
For tests involving custom types with incomplete type information, disable type validation as a last resort. Prefer specifying types that exist:
@Test
void withCustomType() {
rewriteRun(
spec -> spec.typeValidationOptions(TypeValidation.none()),
java(
// test code
)
);
}
Suppressing IDE Warnings in Tests
When testing code with intentional issues (that the recipe will fix), suppress IDE warnings:
// Single test method
@SuppressWarnings("RedundantCast")
@Test
void testRedundantCast() { ... }
// Multiple tests with same warning - move to class level
@SuppressWarnings({"ConstantConditions", "RedundantCast"})
class MyRecipeTest implements RewriteTest { ... }
Common suppressions: "RedundantCast", "ConstantConditions", "unused", "unchecked"
IDE Support with Language Comments
Add //language=java before string templates to enable IDE syntax highlighting.
When using java("before", "after") with no customization, place the comment before java:
//language=java
java(
"""
public class Before { }
""",
"""
public class After { }
"""
)
When there's customization or multiple java() calls, place comments on individual strings:
spec -> spec.typeValidationOptions(TypeValidation.none()),
//language=java
java(
"""
public class Test { }
"""
)
Do NOT add //language=java to JavaTemplate strings containing parameters like #{any()} or #{} — these aren't valid Java and will cause IDE errors.
Test Coverage
Ensure comprehensive coverage including:
- Basic cases
- Edge cases (custom types, fully qualified types)
- Cases where the recipe should NOT make changes
- Import handling scenarios
- Formatting preservation
Maven POM Dependency Ordering
Maven POM files should follow a consistent dependency ordering structure. See the pom-ordering skill for detailed guidelines.
Converted and distributed by TomeVault — claim your Tome and manage your conversions.