junit5 icon indicating copy to clipboard operation
junit5 copied to clipboard

Detect and report usage of `@Rule` in JUnit Jupiter

Open C-Otto opened this issue 3 months ago • 1 comments

With JUnit 5, support for org.junit.Rule has been removed (and replaced by @ExtendWith). However, test classes run by JUnit 5 silently ignore the @Rule annotation, possibly causing unintended results. If tests fail due to the rule not being considered, this isn't a huge issue.

However, for example with AssertJ's JUnitSoftAssertions rule, the change may also remain undetected with assertions not being checked. The rule automatically calls softly.assertAll at the end of each test method execution, which is necessary for tests using soft assertions to fail.

Failing with JUnit 4, but passing with JUnit 5 (corresponding imports for @Test):

@Rule public final JUnitSoftAssertions softly = new JUnitSoftAssertions();
@Test public void test() {
    softly.assertThat(true).isFalse();
}

In my project, we used OpenRewrite to (partially) transform older test classes (based on JUnit 4, using the JUnitSoftAssertions rule) to JUnit 5. This rewrite logic does not seem to consider rules. As one may also manually convert JUnit 4 test classes to JUnit 5, I see this issue unrelated to the logic implemented in OpenRewrite.

I'd like to see a detection similar to #242.

JUnitSoftAssertions: https://joel-costigliola.github.io/assertj/core/api/org/assertj/core/api/JUnitSoftAssertions.html

C-Otto avatar Sep 10 '25 14:09 C-Otto

Regarding AssertJ, just FYI, we plan to deprecate for removal all JUnit 4 support in version 4.

scordio avatar Sep 10 '25 14:09 scordio