Indeed, as @Quwin suggested, accoridng to JUnit 4.12 API doc,
TestRule
can do everything that could be done previously with
methods annotated with @Before
, @After
, @BeforeClass
, or
@AfterClass
, but TestRule
s are (1) more powerful, and (2) more easily shared
between projects and classes.
Ways that TestRule
s are more powerful:
There are known implementing classes of the TestRule
, which are some usefuls rules you can use out-of-the-box,
For examples of how this can be useful, see these provided TestRules, or write your own:
ErrorCollector
: collect multiple errors in one test method
ExpectedException
: make flexible assertions about thrown exceptions
ExternalResource
: start and stop a server, for example
TemporaryFolder
: create fresh files, and delete after test
TestName
: remember the test name for use during the method
TestWatcher
: add logic at events during method execution
Timeout
: cause test to fail after a set time
Verifier
: fail test if object state ends up incorrect
Another benefit of rules, is that multiple rules can be used in a single test case. You may want to use RuleChain
to specify the order in which the rules should be run.