Skip to main content

Migrate to AssertJ from JUnit Asserts

In this tutorial, we'll use OpenRewrite to perform an automated migration from JUnit Asserts to AssertJ. AssertJ is a Java library that provides a rich set of assertions and truly helpful error messages, improves test code readability, and is designed to be super easy to use within your favorite IDE.

Example Configuration

The migrate to AssertJ recipe can be applied by adding OpenRewrite's plugin to your project and including a dependency on rewrite-testing-frameworks:

This recipe has no required configuration options. It can be activated by adding a dependency on `org.openrewrite.recipe:rewrite-testing-frameworks` in your build file or by running a shell command (in which case no build changes are needed):

  1. Add the following to your build.gradle file:
    build.gradle
    plugins {
    id("org.openrewrite.rewrite") version("latest.release")
    }

    rewrite {
    activeRecipe("org.openrewrite.java.testing.assertj.JUnitToAssertj")
    }

    repositories {
    mavenCentral()
    }

    dependencies {
    rewrite("org.openrewrite.recipe:rewrite-testing-frameworks:3.33.0")
    }
  2. Run gradle rewriteRun to run the recipe.

At this point, you're ready to execute the migration by running mvn rewrite:run or gradlew rewriteRun. After running the migration you can inspect the results with git diff (or equivalent), manually fix anything that wasn't able to be migrated automatically, and commit the results.

Before and After

For the full list of changes, this recipe will make, see its reference page.

package org.openrewrite.example;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import static org.junit.jupiter.api.Assertions.assertThrows;

public class ExampleJunitTestClass {

@Test
void someTest() {
try {
QueryRegistry queryRegistry = new QueryRegistry.Builder().build();
fail();
} catch (IllegalArgumentException ignored) {
}

// ...

assertEquals(1, currentSubs.size());
assertEquals("myPrefix_subId", currentSubs.get(0).getSubscriptionId());
assertTrue(allSubscriptions.containsKey("myApp"));
}

@Test
void shouldFailToInitializeWithMissingTable() {
when(catalog.loadTable(any())).thenThrow(new RuntimeException());
IcebergWriterStage stage = new IcebergWriterStage();
assertThrows(RuntimeException.class, () -> stage.init(context));
}
}

See how this recipe works across multiple open-source repositories

Run this recipe on OSS repos at scale with the Moderne SaaS.

The community edition of the Moderne platform enables you to easily run recipes across thousands of open-source repositories.

Please contact Moderne for more information about safely running the recipes on your own codebase in a private SaaS.