View Javadoc
1   package org.junit.tests.experimental.rules;
2   
3   import static java.util.Arrays.asList;
4   import static org.junit.Assert.assertEquals;
5   import static org.junit.Assert.assertTrue;
6   import static org.junit.experimental.results.PrintableResult.testResult;
7   import static org.junit.rules.RuleChain.outerRule;
8   
9   import java.util.ArrayList;
10  import java.util.List;
11  
12  import org.junit.Rule;
13  import org.junit.Test;
14  import org.junit.rules.RuleChain;
15  import org.junit.rules.TestWatcher;
16  import org.junit.runner.Description;
17  
18  public class RuleChainTest {
19      private static final List<String> LOG = new ArrayList<String>();
20  
21      private static class LoggingRule extends TestWatcher {
22          private final String label;
23  
24          public LoggingRule(String label) {
25              this.label = label;
26          }
27  
28          @Override
29          protected void starting(Description description) {
30              LOG.add("starting " + label);
31          }
32  
33          @Override
34          protected void finished(Description description) {
35              LOG.add("finished " + label);
36          }
37      }
38  
39      public static class UseRuleChain {
40          @Rule
41          public final RuleChain chain = outerRule(new LoggingRule("outer rule"))
42                  .around(new LoggingRule("middle rule")).around(
43                          new LoggingRule("inner rule"));
44  
45          @Test
46          public void example() {
47              assertTrue(true);
48          }
49      }
50  
51      @Test
52      public void executeRulesInCorrectOrder() throws Exception {
53          testResult(UseRuleChain.class);
54          List<String> expectedLog = asList("starting outer rule",
55                  "starting middle rule", "starting inner rule",
56                  "finished inner rule", "finished middle rule",
57                  "finished outer rule");
58          assertEquals(expectedLog, LOG);
59      }
60  }