1 /* 2 * Copyright (C) 2015 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 package vogar.target.junit; 17 18 import com.google.common.annotations.VisibleForTesting; 19 import java.util.Collections; 20 import java.util.Comparator; 21 import java.util.LinkedHashSet; 22 import java.util.List; 23 import java.util.Set; 24 import java.util.concurrent.atomic.AtomicReference; 25 import javax.annotation.Nullable; 26 import junit.framework.AssertionFailedError; 27 import vogar.monitor.TargetMonitor; 28 import vogar.target.Runner; 29 import vogar.target.RunnerFactory; 30 import vogar.target.TestEnvironment; 31 32 /** 33 * Creates a Runner for JUnit 3 or JUnit 4 tests. 34 */ 35 public class JUnitRunnerFactory implements RunnerFactory { 36 37 @Override @Nullable 38 public Runner newRunner(TargetMonitor monitor, String qualification, 39 Class<?> klass, AtomicReference<String> skipPastReference, 40 TestEnvironment testEnvironment, int timeoutSeconds, boolean profile, 41 String[] args) { 42 if (supports(klass)) { 43 List<VogarTest> tests = createVogarTests(klass, qualification, args); 44 return new JUnitRunner(monitor, skipPastReference, testEnvironment, timeoutSeconds, 45 tests); 46 } else { 47 return null; 48 } 49 } 50 51 @VisibleForTesting 52 public static List<VogarTest> createVogarTests( 53 Class<?> testClass, String qualification, String[] args) { 54 55 Set<String> methodNames = new LinkedHashSet<>(); 56 if (qualification != null) { 57 methodNames.add(qualification); 58 } 59 Collections.addAll(methodNames, args); 60 61 final List<VogarTest> tests; 62 if (Junit3.isJunit3Test(testClass)) { 63 tests = Junit3.classToVogarTests(testClass, methodNames); 64 } else if (Junit4.isJunit4Test(testClass)) { 65 tests = Junit4.classToVogarTests(testClass, methodNames); 66 } else { 67 throw new AssertionFailedError("Unknown JUnit type: " + testClass.getName()); 68 } 69 70 // Sort the tests to ensure consistent ordering. 71 Collections.sort(tests, new Comparator<VogarTest>() { 72 @Override 73 public int compare(VogarTest o1, VogarTest o2) { 74 return o1.toString().compareTo(o2.toString()); 75 } 76 }); 77 return tests; 78 } 79 80 @VisibleForTesting 81 boolean supports(Class<?> klass) { 82 return Junit3.isJunit3Test(klass) || Junit4.isJunit4Test(klass); 83 } 84 }