1/*
2 * Copyright (C) 2012 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 */
16package com.android.test.runner.junit4;
17
18import android.app.Instrumentation;
19
20import com.android.test.InjectContext;
21import com.android.test.InjectInstrumentation;
22
23import org.junit.runner.Runner;
24import org.junit.runners.model.RunnerBuilder;
25
26import java.lang.reflect.Field;
27
28/**
29 * A {@link RunnerBuilder} that will build customized runners needed to handle {@link InjectContext}
30 * and {@link InjectInstrumentation}.
31 */
32public class AndroidJUnit4Builder extends RunnerBuilder {
33
34    private final Instrumentation mInstrumentation;
35    private boolean mSkipExecution;
36
37    public AndroidJUnit4Builder(Instrumentation instr, boolean skipExecution) {
38        mInstrumentation = instr;
39        mSkipExecution = skipExecution;
40    }
41
42    @Override
43    public Runner runnerForClass(Class<?> testClass) throws Throwable {
44        if (mSkipExecution) {
45            return new NonExecutingJUnit4ClassRunner(testClass);
46        }
47        if (hasInjectedFields(testClass)) {
48            return new AndroidJUnit4ClassRunner(testClass, mInstrumentation);
49        }
50        return null;
51    }
52
53    private boolean hasInjectedFields(Class<?> testClass) {
54        // TODO: evaluate performance of this method, would be nice to utilize the annotation
55        // caching mechanism of ParentRunner
56        for (Field field : testClass.getDeclaredFields()) {
57            if (field.isAnnotationPresent(InjectInstrumentation.class)) {
58                return true;
59            }
60            if (field.isAnnotationPresent(InjectContext.class)) {
61                return true;
62            }
63        }
64        return false;
65    }
66}
67