Class RuleChain

java.lang.Object
org.junit.rules.RuleChain
All Implemented Interfaces:
TestRule

public class RuleChain extends Object implements TestRule
The RuleChain can be used for creating composite rules. You create a RuleChain with outerRule(TestRule) and subsequent calls of around(TestRule):
 public abstract class CompositeRules {
   public static TestRule extendedLogging() {
     return RuleChain.outerRule(new LoggingRule("outer rule"))
                     .around(new LoggingRule("middle rule"))
                     .around(new LoggingRule("inner rule"));
   }
 }
 
 public class UseRuleChain {
   @Rule
   public final TestRule extendedLogging = CompositeRules.extendedLogging();

   @Test
   public void example() {
     assertTrue(true);
   }
 }
 
writes the log
 starting outer rule
 starting middle rule
 starting inner rule
 finished inner rule
 finished middle rule
 finished outer rule
 
In older versions of JUnit (before 4.13) RuleChain was used for ordering rules. We recommend to not use it for this purpose anymore. You can use the attribute order of the annotation Rule or ClassRule for ordering rules.
Since:
4.10
See Also:
  • Field Details

    • EMPTY_CHAIN

      private static final RuleChain EMPTY_CHAIN
    • rulesStartingWithInnerMost

      private List<TestRule> rulesStartingWithInnerMost
  • Constructor Details

  • Method Details

    • emptyRuleChain

      public static RuleChain emptyRuleChain()
      Returns a RuleChain without a TestRule. This method may be the starting point of a RuleChain.
      Returns:
      a RuleChain without a TestRule.
    • outerRule

      public static RuleChain outerRule(TestRule outerRule)
      Returns a RuleChain with a single TestRule. This method is the usual starting point of a RuleChain.
      Parameters:
      outerRule - the outer rule of the RuleChain.
      Returns:
      a RuleChain with a single TestRule.
    • around

      public RuleChain around(TestRule enclosedRule)
      Create a new RuleChain, which encloses the given TestRule with the rules of the current RuleChain.
      Parameters:
      enclosedRule - the rule to enclose; must not be null.
      Returns:
      a new RuleChain.
      Throws:
      NullPointerException - if the argument enclosedRule is null
    • apply

      public Statement apply(Statement base, Description description)
      Modifies the method-running Statement to implement this test-running rule.
      Specified by:
      apply in interface TestRule
      Parameters:
      base - The Statement to be modified
      description - A Description of the test implemented in base
      Returns:
      a new statement, which may be the same as base, a wrapper around base, or a completely new Statement.