Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Simple method to search Java classpath to find @Test annotated JUnit tests
/**
* Get all test classes starting from a base package path.
* <p>
* Example use:
* <pre>
* UnitTestScanner scanner = new UnitTestScanner();
* List<Class<?>> list = scanner.getTestClasses("com.octodecillion.test");
* </pre>
* @param basePackage package where search will start
* @param debug if true output more info
* @return list of classes found
* @throws ClassNotFoundException if any test found
*/
public List<Class<? extends Object>> getTestClasses(String basePackage, boolean debug) throws ClassNotFoundException {
final ArrayList<Class<?>> list = Lists.newArrayList();
ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
provider.addIncludeFilter(testFilter(list,debug));
provider.findCandidateComponents(basePackage);
if(debug){
for( Class<?> cl : list){
String klazzName = cl.getName();
System.out.println(klazzName);
}
}
return list;
}
/**
* Get a filter that accepts only Classes containing methods annotated with @Test or @RunWith.
*
* @param debug
* @param list
* @return
*/
private TypeFilter testFilter(final ArrayList<Class<?>> list, final boolean debug) {
return new TypeFilter() {
// TODO: just make this an external class.
public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException {
ClassMetadata meta = metadataReader.getClassMetadata();
if (meta.hasEnclosingClass() || !meta.isConcrete()) {
return false;
}
boolean accepted = false;
try {
Class<?> clazz = Class.forName(meta.getClassName(), false, ClassUtils.getDefaultClassLoader());
Method[] methods = clazz.getMethods();
for (Method method : methods) {
if (accept(method)) {
accepted = true;
break;
}
}
if(accepted){
list.add(clazz);
}
} catch (Exception e) {
if(debug){
e.printStackTrace();
}
}
return result;
}
/**
* Is the method a test?
*
* @param method
* @return
*/
private boolean accept(Method method) {
return method.getAnnotation(Test.class) != null || method.getAnnotation(RunWith.class) != null;
}
};
}
/**
* Get all test classes starting from a base package path.
* @see {@link #getTestClasses(String, boolean)}
*
* @param basePackage package where search will start
* @return list of classes found
* @throws ClassNotFoundException if any test found
*/
public List<Class<? extends Object>> getTestClasses(String basePackage) throws ClassNotFoundException {
return getTestClasses(basePackage, false);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment