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