JUnit Rule
Definition
A JUnit Rule is a reusable object that wraps a JUnit 4 test method (or a whole class with @ClassRule) so setup, cleanup, timeouts, and extra checks live in one place. You implement TestRule or extend ExternalResource, then put a public field annotated with @Rule on each test class that needs it. That is the same job as setUp and tearDown, without copying those methods into every class. JUnit 5 and 6 replace Rules with extensions.
Key Takeaways
- A Rule wraps the test
Statement: work beforeevaluate()is setup, work infinallyafter it is cleanup. - The
@Rulefield must be public and non-static.@ClassRulefields must be public and static. - Write a Rule when more than one test class needs the same lifecycle. Keep
@Before/@Afterfor logic that is unique to one class. - On new Jupiter tests, prefer an Extension instead of adding more
TestRuleclasses.
How It Works
- The JUnit 4 runner finds
@Rulewith reflection, the same way it finds@Test. applyreceives the current testStatementand returns a wrapperStatement.- The wrapper runs around
@Before, the test method, and@After. - Several rules nest.
RuleChainor@Rule(order = ...)makes that order explicit.
Where It Is Used
- Teams extract a
DatabaseResetRuleso every service test starts from an empty schema. - JUnit ships
TemporaryFolder,Timeout,ExpectedException, andExternalResource. - Older Android Espresso tests use
ActivityTestRule, which is a Rule that launches an Activity.