View Javadoc
1   package org.junit.rules;
2   
3   import org.junit.runner.Description;
4   import org.junit.runners.model.Statement;
5   
6   /**
7    * A TestRule is an alteration in how a test method, or set of test methods,
8    * is run and reported.  A {@link TestRule} may add additional checks that cause
9    * a test that would otherwise fail to pass, or it may perform necessary setup or
10   * cleanup for tests, or it may observe test execution to report it elsewhere.
11   * {@link TestRule}s can do everything that could be done previously with
12   * methods annotated with {@link org.junit.Before},
13   * {@link org.junit.After}, {@link org.junit.BeforeClass}, or
14   * {@link org.junit.AfterClass}, but they are more powerful, and more easily
15   * shared
16   * between projects and classes.
17   *
18   * The default JUnit test runners for suites and
19   * individual test cases recognize {@link TestRule}s introduced in two different
20   * ways.  {@link org.junit.Rule} annotates method-level
21   * {@link TestRule}s, and {@link org.junit.ClassRule}
22   * annotates class-level {@link TestRule}s.  See Javadoc for those annotations
23   * for more information.
24   *
25   * Multiple {@link TestRule}s can be applied to a test or suite execution. The
26   * {@link Statement} that executes the method or suite is passed to each annotated
27   * {@link org.junit.Rule} in turn, and each may return a substitute or modified
28   * {@link Statement}, which is passed to the next {@link org.junit.Rule}, if any. For
29   * examples of how this can be useful, see these provided TestRules,
30   * or write your own:
31   *
32   * <ul>
33   *   <li>{@link ErrorCollector}: collect multiple errors in one test method</li>
34   *   <li>{@link ExpectedException}: make flexible assertions about thrown exceptions</li>
35   *   <li>{@link ExternalResource}: start and stop a server, for example</li>
36   *   <li>{@link TemporaryFolder}: create fresh files, and delete after test</li>
37   *   <li>{@link TestName}: remember the test name for use during the method</li>
38   *   <li>{@link TestWatcher}: add logic at events during method execution</li>
39   *   <li>{@link Timeout}: cause test to fail after a set time</li>
40   *   <li>{@link Verifier}: fail test if object state ends up incorrect</li>
41   * </ul>
42   *
43   * @since 4.9
44   */
45  public interface TestRule {
46      /**
47       * Modifies the method-running {@link Statement} to implement this
48       * test-running rule.
49       *
50       * @param base The {@link Statement} to be modified
51       * @param description A {@link Description} of the test implemented in {@code base}
52       * @return a new statement, which may be the same as {@code base},
53       *         a wrapper around {@code base}, or a completely new Statement.
54       */
55      Statement apply(Statement base, Description description);
56  }