Hier ist das Stück Code, das ich geschrieben habe, um alle Testfälle in meinem JUnit-Projekt zu finden. Es liest die Dateien (unter dem im Code erwähnten Paket) und findet mithilfe von Reflection-APIs die Testfälle mit der Annotation "@Test" und auch diejenigen, die mit "test" beginnen, aber nicht die Annotation @Test haben
public class TestCaseCount {
private static List<Class> getClasses(String packageName)
throws ClassNotFoundException, IOException {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
assert classLoader != null;
String path = packageName.replace('.', '/');
Enumeration<URL> resources = classLoader.getResources(path);
List<File> dirs = new ArrayList<File>();
while (resources.hasMoreElements()) {
URL resource = resources.nextElement();
dirs.add(new File(resource.getFile()));
}
ArrayList<Class> classes = new ArrayList<Class>();
for (File directory : dirs) {
classes.addAll(findClasses(directory, packageName));
}
return classes /* .toArray(new Class[classes.size()]) */;
}
private static List<Class> findClasses(File directory, String packageName)
throws ClassNotFoundException {
List<Class> classes = new ArrayList<Class>();
if (!directory.exists()) {
return classes;
}
File[] files = directory.listFiles();
for (File file : files) {
if (file.isDirectory()) {
assert !file.getName().contains(".");
classes.addAll(findClasses(file, packageName + "." + file.getName()));
} else if (file.getName().endsWith(".class")) {
classes.add(Class.forName(packageName + '.'
+ file.getName().substring(0, file.getName().length() - 6)));
}
}
return classes;
}
public static void main(String args[]) {
ArrayList<Class> classes = new ArrayList<Class>();
try {
// Feature1 Test Cases
classes.addAll(TestCaseCount.getClasses("mypackage.feature1.tests"));
// Feature2 Test Cases
classes.addAll(TestCaseCount.getClasses("mypackage.feature2.tests1"));
classes.addAll(TestCaseCount.getClasses("mypackage.feature2.tests2"));
// Feature3 Test Cases
classes.addAll(TestCaseCount.getClasses("mypackage.feature3.tests"));
} catch (Exception e) {
e.printStackTrace();
}
int testcaseCount = 0;
for (Class cl : classes) {
System.out.println("Test Class Name : " + cl.getName());
Method[] methods = cl.getDeclaredMethods();
for (Method method : methods) {
Annotation[] annotations = method.getDeclaredAnnotations();
if (annotations.length == 0 && method.getName().startsWith("test")) {
testcaseCount++;
} else {
for (Annotation annotation : annotations) {
if (annotation.annotationType().toString()
.equals("interface org.junit.Test")) {
testcaseCount++;
}
}
}
}
}
System.out.println("Total Test Cases " + testcaseCount);
}
}