Skip to main content

AssertJ Best Practices

To switch to AssertJ and apply all associated best practices, you can use the OpenRewrite recipe org.openrewrite.java.testing.assertj.Assertj.

This recipe applies a comprehensive set of changes:

  • Converts JUnit assertions -- assertEquals, assertTrue, assertFalse, assertNull, assertNotNull all become fluent assertThat(...) calls
  • Converts Hamcrest assertions -- assertThat(value, is(...)) and other matchers become AssertJ equivalents
  • Improves existing AssertJ -- chains separate assertions, replaces assertThat(x.size()).isEqualTo(n) with assertThat(x).hasSize(n), removes redundant isNotNull() checks
  • Adds AssertJ dependency if not already present, and removes unused Hamcrest dependencies
tip

This is a great recipe to run on the books module first to see the changes before applying it to your own projects.

You can run the migration recipe using one of the following methods.

The Moderne CLI allows you to run OpenRewrite recipes on your project without needing to modify your build files, against serialized Lossless Semantic Tree (LST) of your project for a considerable performance boost & across projects.

You will need to have configured the Moderne CLI on your machine before you can run the following command.

  1. If project serialized Lossless Semantic Tree is not yet available locally, then build the LST. This is only needed the first time, or after extensive changes:
    shell
    mod build ~/workspace/
  2. If the recipe is not available locally yet, then you can install it once using:
    shell
    mod config recipes jar install org.openrewrite.recipe:rewrite-testing-frameworks:LATEST
  3. Run the recipe.
    shell
    mod run ~/workspace/ --recipe org.openrewrite.java.testing.assertj.Assertj