ClassRule (JUnit API)
Date: 2011-08-22

Overview | Package | Class | Tree | Deprecated | Index | Help
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: REQUIRED | OPTIONAL | DETAIL: ELEMENT

## org.junit
Annotation Type ClassRule

    @Retention(value=RUNTIME)
    @Target(value=FIELD)
    public @interface ClassRule

Annotates static fields that contain rules. Such a field must be public, static, and a subtype of `TestRule`. The `Statement` passed to the `TestRule` will run any `BeforeClass` 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 a `Suite`), and finally any `AfterClass` methods. The statement passed to the `TestRule` will never throw an exception, and throwing an exception from the `TestRule` will result in undefined behavior. This means that some `TestRule`s, such as `ErrorCollector`, `ExpectedException`, and `Timeout`, have undefined behavior when used as `ClassRule`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. 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();
                    };
            };
     }

For more information and more examples, see `TestRule`.

Overview | Package | Class | Tree | Deprecated | Index | Help
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: REQUIRED | OPTIONAL | DETAIL: ELEMENT