1 package org.junit.tests.experimental.rules;
2
3 import static org.junit.Assert.assertThat;
4 import static org.junit.Assert.assertTrue;
5 import static org.junit.experimental.results.PrintableResult.testResult;
6 import static org.junit.experimental.results.ResultMatchers.isSuccessful;
7
8 import java.util.LinkedList;
9 import java.util.List;
10
11 import org.junit.Test;
12 import org.junit.rules.MethodRule;
13 import org.junit.rules.TestRule;
14 import org.junit.runner.Description;
15 import org.junit.runner.RunWith;
16 import org.junit.runners.BlockJUnit4ClassRunner;
17 import org.junit.runners.model.FrameworkMethod;
18 import org.junit.runners.model.InitializationError;
19 import org.junit.runners.model.Statement;
20
21 public class BlockJUnit4ClassRunnerOverrideTest {
22 public static class FlipBitRule implements MethodRule {
23 public Statement apply(final Statement base, FrameworkMethod method,
24 final Object target) {
25 return new Statement() {
26 @Override
27 public void evaluate() throws Throwable {
28 target.getClass().getField("flipBit").set(target, true);
29 base.evaluate();
30 }
31 };
32 }
33
34 }
35
36 public static class OverrideRulesRunner extends BlockJUnit4ClassRunner {
37 public OverrideRulesRunner(Class<?> klass) throws InitializationError {
38 super(klass);
39 }
40
41 @Override
42 protected List<MethodRule> rules(Object test) {
43 final LinkedList<MethodRule> methodRules = new LinkedList<MethodRule>(
44 super.rules(test));
45 methodRules.add(new FlipBitRule());
46 return methodRules;
47 }
48 }
49
50 @RunWith(OverrideRulesRunner.class)
51 public static class OverrideRulesTest {
52 public boolean flipBit = false;
53
54 @Test
55 public void testFlipBit() {
56 assertTrue(flipBit);
57 }
58 }
59
60 @Test
61 public void overrideRulesMethod() {
62 assertThat(testResult(OverrideTestRulesTest.class), isSuccessful());
63 }
64
65 public static class OverrideTestRulesRunner extends BlockJUnit4ClassRunner {
66 public OverrideTestRulesRunner(Class<?> klass)
67 throws InitializationError {
68 super(klass);
69 }
70
71 @Override
72 protected List<TestRule> getTestRules(final Object test) {
73 final LinkedList<TestRule> methodRules = new LinkedList<TestRule>(
74 super.getTestRules(test));
75 methodRules.add(new TestRule() {
76 public Statement apply(Statement base, Description description) {
77 return new FlipBitRule().apply(base, null, test);
78 }
79 });
80 return methodRules;
81 }
82 }
83
84 @RunWith(OverrideTestRulesRunner.class)
85 public static class OverrideTestRulesTest extends OverrideRulesTest {
86 }
87
88 @Test
89 public void overrideTestRulesMethod() {
90 assertThat(testResult(OverrideRulesTest.class), isSuccessful());
91 }
92 }