Annotation Type ClassRule
-
@Retention(RUNTIME) @Target({FIELD,METHOD}) public @interface ClassRule
Annotates static fields that reference rules or methods that return them. A field must be public, static, and a subtype ofTestRule
. A method must be public static, and return a subtype ofTestRule
.The
Statement
passed to theTestRule
will run anyBeforeClass
methods, then the entire body of the test class (all contained methods, if it is a standard JUnit test class, or all contained classes, if it is aSuite
), and finally anyAfterClass
methods.The statement passed to the
TestRule
will never throw an exception, and throwing an exception from theTestRule
will result in undefined behavior. This means that someTestRule
s, such asErrorCollector
,ExpectedException
, andTimeout
, have undefined behavior when used asClassRule
s.If there are multiple annotated
ClassRule
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. However, Rules defined by fields will always be applied after Rules defined by methods, i.e. the Statements returned by the former will be executed around those returned by the latter.Usage
For example, here is a test suite that connects to a server once before all the test classes run, and disconnects after they are finished:
@RunWith(Suite.class) @SuiteClasses({A.class, B.class, C.class}) public class UsesExternalResource { public static Server myServer= new Server(); @ClassRule public static ExternalResource resource= new ExternalResource() { @Override protected void before() throws Throwable { myServer.connect(); } @Override protected void after() { myServer.disconnect(); } }; }
and the same using a method
@RunWith(Suite.class) @SuiteClasses({A.class, B.class, C.class}) public class UsesExternalResource { public static Server myServer= new Server(); @ClassRule public static ExternalResource getResource() { return new ExternalResource() { @Override protected void before() throws Throwable { myServer.connect(); } @Override protected void after() { myServer.disconnect(); } }; } }
For more information and more examples, see
TestRule
.Ordering
You can use
order()
if you want to have control over the order in which the Rules are applied.public class ThreeClassRules { @ClassRule(order = 0) public static LoggingRule outer = new LoggingRule("outer rule"); @ClassRule(order = 1) public static LoggingRule middle = new LoggingRule("middle rule"); @ClassRule(order = 2) public static LoggingRule inner = new LoggingRule("inner rule"); // ... }
- Since:
- 4.9
-
-
Optional Element Summary
Optional Elements Modifier and Type Optional Element Description int
order
Specifies the order in which rules are applied.
-
-
-
Element Detail
-
order
int order
Specifies the order in which rules are applied. The rules with a higher value are inner.- Since:
- 4.13
- Default:
- -1
-
-