001 package org.junit.rules; 002 003 import org.junit.runner.Description; 004 import org.junit.runners.model.Statement; 005 006 /** 007 * A TestRule is an alteration in how a test method, or set of test methods, 008 * is run and reported. A {@link TestRule} may add additional checks that cause 009 * a test that would otherwise fail to pass, or it may perform necessary setup or 010 * cleanup for tests, or it may observe test execution to report it elsewhere. 011 * {@link TestRule}s can do everything that could be done previously with 012 * methods annotated with {@link org.junit.Before}, 013 * {@link org.junit.After}, {@link org.junit.BeforeClass}, or 014 * {@link org.junit.AfterClass}, but they are more powerful, and more easily 015 * shared 016 * between projects and classes. 017 * 018 * The default JUnit test runners for suites and 019 * individual test cases recognize {@link TestRule}s introduced in two different 020 * ways. {@link org.junit.Rule} annotates method-level 021 * {@link TestRule}s, and {@link org.junit.ClassRule} 022 * annotates class-level {@link TestRule}s. See Javadoc for those annotations 023 * for more information. 024 * 025 * Multiple {@link TestRule}s can be applied to a test or suite execution. The 026 * {@link Statement} that executes the method or suite is passed to each annotated 027 * {@link org.junit.Rule} in turn, and each may return a substitute or modified 028 * {@link Statement}, which is passed to the next {@link org.junit.Rule}, if any. For 029 * examples of how this can be useful, see these provided TestRules, 030 * or write your own: 031 * 032 * <ul> 033 * <li>{@link ErrorCollector}: collect multiple errors in one test method</li> 034 * <li>{@link ExpectedException}: make flexible assertions about thrown exceptions</li> 035 * <li>{@link ExternalResource}: start and stop a server, for example</li> 036 * <li>{@link TemporaryFolder}: create fresh files, and delete after test</li> 037 * <li>{@link TestName}: remember the test name for use during the method</li> 038 * <li>{@link TestWatcher}: add logic at events during method execution</li> 039 * <li>{@link Timeout}: cause test to fail after a set time</li> 040 * <li>{@link Verifier}: fail test if object state ends up incorrect</li> 041 * </ul> 042 * 043 * @since 4.9 044 */ 045 public interface TestRule { 046 /** 047 * Modifies the method-running {@link Statement} to implement this 048 * test-running rule. 049 * 050 * @param base The {@link Statement} to be modified 051 * @param description A {@link Description} of the test implemented in {@code base} 052 * @return a new statement, which may be the same as {@code base}, 053 * a wrapper around {@code base}, or a completely new Statement. 054 */ 055 Statement apply(Statement base, Description description); 056 }