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 com.google.common.base.Function;
20import java.util.ArrayList;
21import java.util.Collection;
22import org.junit.runner.Runner;
23import org.junit.runners.BlockJUnit4ClassRunner;
24import org.junit.runners.JUnit4;
25import org.junit.runners.model.RunnerBuilder;
26import vogar.target.junit.junit3.AlternateSuiteMethodBuilder;
27
28/**
29 * A composite {@link RunnerBuilder} that will ask each of its list of {@link RunnerBuilder} to
30 * create a runner, returning the result of the first that does so, or null if none match.
31 */
32public class VogarRunnerBuilder extends RunnerBuilder {
33
34    private static final ReplaceRunnerFunction MAPPING_FUNCTION = new ReplaceRunnerFunction();
35
36    private final RunnerParams runnerParams;
37    private final Collection<RunnerBuilder> builders;
38
39    public VogarRunnerBuilder(RunnerParams runnerParams) {
40        this.runnerParams = runnerParams;
41        builders = new ArrayList<>();
42        builders.add(new MappingAnnotatedBuilder(this, MAPPING_FUNCTION));
43        builders.add(new AlternateSuiteMethodBuilder(runnerParams));
44        builders.add(new VogarTestCaseBuilder(runnerParams));
45        builders.add(new VogarJUnit4Builder(this));
46    }
47
48    public RunnerParams getRunnerParams() {
49        return runnerParams;
50    }
51
52    @Override
53    public Runner runnerForClass(Class<?> testClass) throws Throwable {
54        for (RunnerBuilder builder : builders) {
55            Runner runner = builder.safeRunnerForClass(testClass);
56            if (runner != null) {
57                return runner;
58            }
59        }
60
61        return null;
62    }
63
64    private static class ReplaceRunnerFunction
65            implements Function<Class<? extends Runner>, Class<? extends Runner>> {
66        @Override
67        public Class<? extends Runner> apply(Class<? extends Runner> runnerClass) {
68            if (runnerClass == JUnit4.class || runnerClass == BlockJUnit4ClassRunner.class) {
69                return VogarBlockJUnit4ClassRunner.class;
70            } else {
71                return runnerClass;
72            }
73        }
74    }
75}
76