openrewrite
OpenRewrite recipe test maintenance. Use when fixing test failures, import ordering issues, type validation problems, IDE warnings, or writing comprehensive recipe tests.
What this skill does
# 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:
```diff
-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:
```java
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:
```java
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:
```java
// 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:
```java
// 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:
1. Third-party packages (org.assertj, org.eclipse.collections, etc.)
2. Blank line
3. Java standard library (`java.*`, `javax.*`)
4. Blank line (if static imports exist)
5. Static imports
### Quick Fix Steps
1. Run the failing test and copy the actual output from the error message
2. Replace the expected output in your test with the actual output
3. Verify the transformation logic is correct (ignore import order)
4. 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
```java
@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:
```java
@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:
```java
// 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`:
```java
//language=java
java(
"""
public class Before { }
""",
"""
public class After { }
"""
)
```
When there's customization or multiple `java()` calls, place comments on individual strings:
```java
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.
Related in Writing & Docs
jax-development
IncludedUse this skill when the user is writing, debugging, profiling, refactoring, reviewing, benchmarking, parallelising, exporting, or explaining JAX code, or when they mention JAX, jax.numpy, jit, grad, value_and_grad, vmap, scan, lax, random keys, pytrees, jax.Array, sharding, Mesh, PartitionSpec, NamedSharding, pmap, shard_map, Pallas, XLA, StableHLO, checkify, profiler, or the JAX repo. It helps turn NumPy or PyTorch-style code into pure functional JAX, fix tracer/control-flow/shape/PRNG bugs, remove recompiles and host-device syncs, choose transforms and sharding strategies, inspect jaxpr/lowering/IR, and benchmark compiled code correctly.
nature-article-writer
IncludedDrafts, rewrites, diagnostically critiques, and style-calibrates primary research manuscripts for Nature and Nature Portfolio journals. Use when the user wants a Nature-style title, summary paragraph or abstract, introduction, results, discussion, methods, figure legends, presubmission enquiry, cover letter, reviewer response, or when a scientific draft sounds generic, jargon-heavy, structurally weak, or AI-ish and needs precise, broad-reader-friendly prose without inventing data, analyses, or references. Best for primary research articles and letters rather than reviews or press releases unless explicitly adapting one.
deckrd
IncludedDocument-driven framework that derives requirements, specifications, implementation plans, and executable tasks from goals through structured AI dialogue. Use when user says "write requirements", "create spec", "plan implementation", "derive tasks", "structure this feature", "break down into tasks", or "document this module". Also use for reverse engineering existing code into docs (/deckrd rev). Do NOT use for direct code writing โ use /deckrd-coder after tasks are generated. Do NOT use when the user only wants to run or fix existing code without planning.
clinical-decision-support
IncludedGenerate professional clinical decision support (CDS) documents for pharmaceutical and clinical research settings, including patient cohort analyses (biomarker-stratified with outcomes) and treatment recommendation reports (evidence-based guidelines with decision algorithms). Supports GRADE evidence grading, statistical analysis (hazard ratios, survival curves, waterfall plots), biomarker integration, and regulatory compliance. Outputs publication-ready LaTeX/PDF format optimized for drug development, clinical research, and evidence synthesis.
handling-sf-data
IncludedSalesforce data operations with 130-point scoring. Use this skill to create, update, delete, bulk import/export, generate test data, and clean up org records using sf CLI and anonymous Apex. TRIGGER when: user creates test data, performs bulk import/export, uses sf data CLI commands, needs data factory patterns for Apex tests, or needs to seed/clean records in a Salesforce org. DO NOT TRIGGER when: SOQL query writing only (use querying-soql), Apex test execution (use running-apex-tests), or metadata deployment (use deploying-metadata).
accelint-ac-to-playwright
IncludedConvert and validate acceptance criteria for Playwright test automation. Use when user asks to (1) review/evaluate/check if AC are ready for automation, (2) assess if AC can be converted as-is, (3) validate AC quality for Playwright, (4) turn AC into tests, (5) generate tests from acceptance criteria, (6) convert .md bullets or .feature Gherkin files to Playwright specs, (7) create test automation from requirements. Handles both bullet-style markdown and Gherkin syntax with JSON test plan generation and validation.