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.ReflectionUtils;
27  import org.apache.maven.surefire.util.ScannerFilter;
28  
29  
30  
31  
32  public class JUnit4TestChecker
33      implements ScannerFilter
34  {
35      private final NonAbstractClassFilter nonAbstractClassFilter;
36  
37      private final Class runWith;
38  
39      private final JUnit3TestChecker jUnit3TestChecker;
40  
41  
42      public JUnit4TestChecker( ClassLoader testClassLoader )
43      {
44          this.jUnit3TestChecker = new JUnit3TestChecker( testClassLoader );
45          this.runWith = getJUnitClass( testClassLoader, org.junit.runner.RunWith.class.getName() );
46          this.nonAbstractClassFilter = new NonAbstractClassFilter();
47      }
48  
49      public boolean accept( Class testClass )
50      {
51          return jUnit3TestChecker.accept( testClass ) || isValidJUnit4Test( testClass );
52      }
53  
54      @SuppressWarnings( { "unchecked" } )
55      private boolean isValidJUnit4Test( Class testClass )
56      {
57          if ( !nonAbstractClassFilter.accept( testClass ) )
58          {
59              return false;
60          }
61  
62          if ( runWith != null )
63          {
64              Annotation runWithAnnotation = testClass.getAnnotation( runWith );
65              if ( runWithAnnotation != null )
66              {
67                  return true;
68              }
69          }
70  
71          Class classToCheck = testClass;
72          while ( classToCheck != null )
73          {
74              if ( checkforTestAnnotatedMethod( classToCheck ) )
75              {
76                  return true;
77              }
78              classToCheck = classToCheck.getSuperclass();
79          }
80          return false;
81      }
82  
83      private boolean checkforTestAnnotatedMethod( Class testClass )
84      {
85          for ( Method lMethod : testClass.getDeclaredMethods() )
86          {
87              for ( Annotation lAnnotation : lMethod.getAnnotations() )
88              {
89                  if ( org.junit.Test.class.isAssignableFrom( lAnnotation.annotationType() ) )
90                  {
91                      return true;
92                  }
93              }
94          }
95          return false;
96      }
97  
98      private Class getJUnitClass( ClassLoader classLoader, String className )
99      {
100         return ReflectionUtils.tryLoadClass( classLoader, className );
101     }
102 
103 }