Annotates fields that contain rules. Such a field must be public, not
static, and a subtype of
TestRule
.
The
Statement
passed
to the
TestRule
will run any
Before
methods,
then the
Test
method, and finally any
After
methods,
throwing an exception if any of these fail. If there are multiple
annotated
Rule
s on a class, they will be applied in an order
that depends on your JVM's implementation of the reflection API, which is
undefined, in general.
For example, here is a test class that creates a temporary folder before
each test method, and deletes it after each:
public static class HasTempFolder {
@Rule
public TemporaryFolder folder= new TemporaryFolder();
@Test
public void testUsingTempFolder() throws IOException {
File createdFile= folder.newFile("myfile.txt");
File createdFolder= folder.newFolder("subfolder");
// ...
}
}
For more information and more examples, see
TestRule
.
Note: for backwards compatibility, this annotation may also mark
fields of type
MethodRule
, which will be honored. However,
this is a deprecated interface and feature.