Annotation Type Rule
@Retention(RUNTIME) @Target({FIELD,METHOD}) public @interface Rule
Annotates fields that reference rules or methods that return a rule. A field must be public, not static, and a subtype ofTestRule
(preferred) orMethodRule
. A method must be public, not static, and must return a subtype ofTestRule
(preferred) orMethodRule
.The
Statement
passed to theTestRule
will run anyBefore
methods, then theTest
method, and finally anyAfter
methods, throwing an exception if any of these fail. If there are multiple annotatedRule
s on a class, they will be applied in order of fields first, then methods. However, if there are multiple fields (or methods) they will be applied in an order that depends on your JVM's implementation of the reflection API, which is undefined, in general. Rules defined by fields will always be applied before Rules defined by methods. You can use aRuleChain
if you want to have control over the order in which the Rules are applied.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"); // ... } }
And the same using a method.
public static class HasTempFolder { private TemporaryFolder folder= new TemporaryFolder(); @Rule public TemporaryFolder getFolder() { return folder; } @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
.- Since:
- 4.7