1 package org.apache.maven.surefire.common.junit4;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 import java.lang.annotation.Annotation;
23 import java.lang.reflect.Method;
24 import org.apache.maven.surefire.NonAbstractClassFilter;
25 import org.apache.maven.surefire.common.junit3.JUnit3TestChecker;
26 import org.apache.maven.surefire.util.ScannerFilter;
27
28 import static org.apache.maven.surefire.util.ReflectionUtils.tryLoadClass;
29
30
31
32
33 public class JUnit4TestChecker
34 implements ScannerFilter
35 {
36 private final NonAbstractClassFilter nonAbstractClassFilter;
37
38 private final Class runWith;
39
40 private final JUnit3TestChecker jUnit3TestChecker;
41
42
43 public JUnit4TestChecker( ClassLoader testClassLoader )
44 {
45 jUnit3TestChecker = new JUnit3TestChecker( testClassLoader );
46 runWith = tryLoadClass( testClassLoader, org.junit.runner.RunWith.class.getName() );
47 nonAbstractClassFilter = new NonAbstractClassFilter();
48 }
49
50 @Override
51 public boolean accept( Class testClass )
52 {
53 return jUnit3TestChecker.accept( testClass ) || isValidJUnit4Test( testClass );
54 }
55
56 @SuppressWarnings( { "unchecked" } )
57 private boolean isValidJUnit4Test( Class testClass )
58 {
59 if ( !nonAbstractClassFilter.accept( testClass ) )
60 {
61 return false;
62 }
63
64 if ( isRunWithPresentInClassLoader() )
65 {
66 Annotation runWithAnnotation = testClass.getAnnotation( runWith );
67 if ( runWithAnnotation != null )
68 {
69 return true;
70 }
71 }
72
73 return lookForTestAnnotatedMethods( testClass );
74 }
75
76 private boolean lookForTestAnnotatedMethods( Class testClass )
77 {
78 Class classToCheck = testClass;
79 while ( classToCheck != null )
80 {
81 if ( checkforTestAnnotatedMethod( classToCheck ) )
82 {
83 return true;
84 }
85 classToCheck = classToCheck.getSuperclass();
86 }
87 return false;
88 }
89
90 public boolean checkforTestAnnotatedMethod( Class testClass )
91 {
92 for ( Method lMethod : testClass.getDeclaredMethods() )
93 {
94 for ( Annotation lAnnotation : lMethod.getAnnotations() )
95 {
96 if ( org.junit.Test.class.isAssignableFrom( lAnnotation.annotationType() ) )
97 {
98 return true;
99 }
100 }
101 }
102 return false;
103 }
104
105 public boolean isRunWithPresentInClassLoader()
106 {
107 return runWith != null;
108 }
109 }