3.3. Limited JUnit 4 Rule Support

As stated above, JUnit Jupiter does not and will not support JUnit 4 rules natively. The JUnit team realizes, however, that many organizations, especially large ones, are likely to have large JUnit 4 code bases that make use of custom rules. To serve these organizations and enable a gradual migration path the JUnit team has decided to support a selection of JUnit 4 rules verbatim within JUnit Jupiter. This support is based on adapters and is limited to those rules that are semantically compatible to the JUnit Jupiter extension model, i.e. those that do not completely change the overall execution flow of the test.

The junit-jupiter-migrationsupport module from JUnit Jupiter currently supports the following three Rule types including subclasses of these types:

  • org.junit.rules.ExternalResource (including org.junit.rules.TemporaryFolder)

  • org.junit.rules.Verifier (including org.junit.rules.ErrorCollector)

  • org.junit.rules.ExpectedException

As in JUnit 4, Rule-annotated fields as well as methods are supported. By using these class-level extensions on a test class such Rule implementations in legacy code bases can be left unchanged including the JUnit 4 rule import statements.

This limited form of Rule support can be switched on by the class-level annotation [@EnableRuleMigrationSupport](https://junit.org/junit5/docs/current/api/org.junit.jupiter.migrationsupport/org/junit/jupiter/migrationsupport/rules/EnableRuleMigrationSupport.html). This annotation is a composed annotation which enables all rule migration support extensions: VerifierSupport, ExternalResourceSupport, and ExpectedExceptionSupport. You may alternatively choose to annotate your test class with @EnableJUnit4MigrationSupport which registers migration support for rules and JUnit 4’s @Ignore annotation (see JUnit 4 @Ignore Support).

However, if you intend to develop a new extension for JUnit 5 please use the new extension model of JUnit Jupiter instead of the rule-based model of JUnit 4.

JUnit 4 Rule support in JUnit Jupiter is currently an experimental feature. Consult the table in Experimental APIs for detail.