summaryrefslogtreecommitdiffstats
path: root/junit4/src/test/java/org/junit/tests/experimental/rules/RuleChainTest.java
blob: e1ea4c57c2dd675a6cbac97675460b30c5ab8067 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package org.junit.tests.experimental.rules;

import static java.util.Arrays.asList;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.experimental.results.PrintableResult.testResult;
import static org.junit.rules.RuleChain.outerRule;

import java.util.ArrayList;
import java.util.List;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.RuleChain;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;

public class RuleChainTest {
	private static final List<String> LOG= new ArrayList<String>();

	private static class LoggingRule extends TestWatcher {
		private final String label;

		public LoggingRule(String label) {
			this.label= label;
		}

		@Override
		protected void starting(Description description) {
			LOG.add("starting " + label);
		}

		@Override
		protected void finished(Description description) {
			LOG.add("finished " + label);
		}
	}

	public static class UseRuleChain {
		@Rule
		public final RuleChain chain= outerRule(new LoggingRule("outer rule"))
				.around(new LoggingRule("middle rule")).around(
						new LoggingRule("inner rule"));

		@Test
		public void example() {
			assertTrue(true);
		}
	}

	@Test
	public void executeRulesInCorrectOrder() throws Exception {
		testResult(UseRuleChain.class);
		List<String> expectedLog= asList("starting outer rule",
				"starting middle rule", "starting inner rule",
				"finished inner rule", "finished middle rule",
				"finished outer rule");
		assertEquals(expectedLog, LOG);
	}
}