Last active
May 1, 2019 12:20
-
-
Save amgadhanafy/b172cf776bfe313762d38480e17f4517 to your computer and use it in GitHub Desktop.
Run all test classes that are extending specific class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.abc.common; | |
import static java.lang.Class.forName; | |
import static java.lang.Thread.currentThread; | |
import java.io.File; | |
import java.io.IOException; | |
import java.net.URL; | |
import java.util.ArrayList; | |
import java.util.Enumeration; | |
import java.util.List; | |
import junit.framework.JUnit4TestAdapter; | |
import junit.framework.TestCase; | |
import junit.framework.TestSuite; | |
public class AllTests extends TestCase { | |
private static final Class<?> SUPER_CLASS = TestBase.class; | |
private static final String PACKAGE = "com.abc"; | |
public static TestSuite suite() throws ClassNotFoundException, IOException { | |
TestSuite suite = new TestSuite(); | |
for (Class<?> claz : getClasses(PACKAGE, SUPER_CLASS)) { | |
suite.addTest(new JUnit4TestAdapter(claz)); | |
System.out.println(claz.getName()); | |
} | |
return suite; | |
} | |
private static ArrayList<Class<?>> getClasses(String packageName, Class<?> superClass) | |
throws ClassNotFoundException, IOException { | |
ClassLoader classLoader = currentThread().getContextClassLoader(); | |
assert classLoader != null; | |
Enumeration<URL> resources = classLoader.getResources(packageName.replace('.', '/')); | |
List<File> dirs = new ArrayList<>(); | |
while (resources.hasMoreElements()) { | |
dirs.add(new File(resources.nextElement().getFile())); | |
} | |
ArrayList<Class<?>> classes = new ArrayList<>(); | |
for (File directory : dirs) { | |
classes.addAll(findClasses(directory, packageName, superClass)); | |
} | |
return classes; | |
} | |
private static List<Class<?>> findClasses(File directory, String packageName, Class<?> superClass) | |
throws ClassNotFoundException { | |
List<Class<?>> classes = new ArrayList<>(); | |
if (directory.exists()) { | |
for (File file : directory.listFiles()) { | |
String fileName = file.getName(); | |
if (file.isDirectory()) { | |
assert !fileName.contains("."); | |
classes.addAll(findClasses(file, packageName + "." + fileName, superClass)); | |
} else if (fileName.endsWith("Test.class")) { | |
Class<?> testClass = forName(packageName + '.' + fileName.substring(0, fileName.length() - 6)); | |
if (testClass.getSuperclass().equals(superClass)) { | |
classes.add((Class<?>) testClass); | |
} | |
} | |
} | |
} | |
return classes; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment