Skip to content

Instantly share code, notes, and snippets.

@MaxMyalkin
Last active June 14, 2016 13:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MaxMyalkin/71833b8fdba313a6e4e0 to your computer and use it in GitHub Desktop.
Save MaxMyalkin/71833b8fdba313a6e4e0 to your computer and use it in GitHub Desktop.
public static void addTests(ClassLoader loader, TestSuite suite) {
try {
Class[] classes = getClasses("ru.mail.mailbox.cmd.server", loader);
System.out.println("class size " + classes.length);
for(Class clazz : classes) {
for(Method method : clazz.getDeclaredMethods()) {
for(Annotation annotation : method.getAnnotations()) {
if(annotation instanceof MockMethod) {
// suite.addTest(TestSuite.createTest(clazz, method.getName()));
System.out.println("add method " + method.getName() + " for class " + clazz.getName());
break;
}
}
}
}
} catch (ClassNotFoundException | IOException e) {
System.out.println("exception:" + e.getMessage());
e.printStackTrace();
}
}
private static Class[] getClasses(String packageName, ClassLoader classLoader) throws ClassNotFoundException, IOException {
if(classLoader == null) {
return new Class[0];
}
String path = packageName.replace('.', File.separatorChar);
Enumeration<URL> resources = classLoader.getResources(path);
List<File> dirs = new ArrayList<>();
while (resources.hasMoreElements()) {
URL resource = resources.nextElement();
dirs.add(new File(resource.getFile()));
}
ArrayList<Class> classes = new ArrayList<>();
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<>();
if (!directory.exists()) {
return classes;
}
String classSuffix = ".class";
for (File file : directory.listFiles()) {
if (file.isDirectory() && !file.getName().contains(".")) {
classes.addAll(findClasses(file, packageName + "." + file.getName()));
} else if (file.getName().endsWith(classSuffix)) {
classes.add(Class.forName(packageName + '.' + file.getName().substring(0, file.getName().length() - classSuffix.length())));
}
}
return classes;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment