1 /* 2 * Copyright (C) 2011 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 17 package vogar.target.junit; 18 19 import java.lang.annotation.Annotation; 20 import java.lang.reflect.Method; 21 import java.lang.reflect.Modifier; 22 import org.junit.runner.RunWith; 23 import org.junit.runners.Parameterized; 24 import org.junit.runners.Suite; 25 26 /** 27 * Utilities for manipulating JUnit4 tests. 28 */ 29 public final class Junit4 { Junit4()30 private Junit4() {} 31 isJunit4Test(Class<?> klass)32 public static boolean isJunit4Test(Class<?> klass) { 33 boolean isTestSuite = false; 34 boolean hasSuiteClasses = false; 35 36 boolean concrete = !Modifier.isAbstract(klass.getModifiers()); 37 38 // @RunWith(Suite.class) 39 // @SuiteClasses( ... ) 40 // public class MyTest { ... } 41 // or 42 // @RunWith(Parameterized.class) 43 // public class MyTest { ... } 44 for (Annotation a : klass.getAnnotations()) { 45 Class<?> annotationClass = a.annotationType(); 46 47 if (RunWith.class.isAssignableFrom(annotationClass)) { 48 Class<?> runnerClass = ((RunWith) a).value(); 49 if (Suite.class.isAssignableFrom(runnerClass)) { 50 isTestSuite = true; 51 } else if (Parameterized.class.isAssignableFrom(runnerClass)) { 52 // @Parameterized test classes are instantiated so must be concrete. 53 return concrete; 54 } 55 } else if (Suite.SuiteClasses.class.isAssignableFrom(annotationClass)) { 56 hasSuiteClasses = true; 57 } 58 59 if (isTestSuite && hasSuiteClasses) { 60 // This doesn't instantiate the class so doesn't care if it's abstract. 61 return true; 62 } 63 } 64 65 // Test classes that have methods annotated with @Test are instantiated so must be concrete. 66 if (!concrete) { 67 return false; 68 } 69 70 // public class MyTest { 71 // @Test 72 // public void example() { ... } 73 // } 74 for (Method m : klass.getMethods()) { 75 for (Annotation a : m.getAnnotations()) { 76 if (org.junit.Test.class.isAssignableFrom(a.annotationType())) { 77 return true; 78 } 79 } 80 } 81 82 return false; 83 } 84 } 85