1/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package vogar.target.junit;
18
19import org.junit.Ignore;
20import org.junit.rules.TestRule;
21import org.junit.runner.Description;
22import org.junit.runner.notification.RunNotifier;
23import org.junit.runners.BlockJUnit4ClassRunner;
24import org.junit.runners.model.FrameworkMethod;
25import org.junit.runners.model.InitializationError;
26import org.junit.runners.model.Statement;
27
28/**
29 * Applies global rules, i.e. those provided externally to the tests.
30 */
31public abstract class ApplyGlobalRulesBlockJUnit4ClassRunner extends BlockJUnit4ClassRunner {
32
33    private final TestRule testRule;
34
35    public ApplyGlobalRulesBlockJUnit4ClassRunner(Class<?> klass, TestRule testRule)
36            throws InitializationError {
37        super(klass);
38        this.testRule = testRule;
39    }
40
41    @Override
42    protected void runChild(final FrameworkMethod method, RunNotifier notifier) {
43        // Override to allow it to call abortingRunLeaf as runLeaf is final and so its behavior
44        // cannot be modified by overriding it.
45        Description description = describeChild(method);
46        if (method.getAnnotation(Ignore.class) != null) {
47            notifier.fireTestIgnored(description);
48        } else {
49            ParentRunnerHelper.abortingRunLeaf(methodBlock(method), description, notifier);
50        }
51    }
52
53    @Override
54    protected Statement methodBlock(FrameworkMethod method) {
55        // Override to apply any global TestRules.
56        Statement statement = super.methodBlock(method);
57        statement = testRule.apply(statement, getDescription());
58        return statement;
59    }
60}
61