Reputation: 2078
I'm creating an application to programmatically execute our java webdriver selenium scripts. We use TestNG.
I'm able to launch the classes with a virtual XML file. This works:
XmlSuite suite = new XmlSuite();
suite.setName("TmpSuite");
XmlTest test = new XmlTest(suite);
test.setName("TmpTest");
List<XmlClass> classes = new ArrayList<XmlClass>();
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("browser", "Firefox");
suite.setParameters(parameters);
classes.add(new XmlClass("package.classname"));
test.setXmlClasses(classes) ;
List<XmlSuite> suites = new ArrayList<XmlSuite>();
suites.add(suite);
TestNG tng = new TestNG();
tng.setXmlSuites(suites);
tng.run();
Since the above method uses the package.classname
to execute the class, I need a way to get all our classes; both their package and their class name (We have hundreds of packages).
I use this code to grab all the package.classnames
. In simply scans the /bin/ directory of the project, converting the folder structure into package names and removes the .class extension from the class file. This works, too:
//scans the /bin directory of project to grab all packages/classes
String binPath = "V:\\Selenium\\Scripts\\bin\\";
File dir = new File(binPath);
List<File> files = (List<File>) FileUtils.listFiles(dir, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE);
List<String> classNames = new ArrayList<String>(300);
for (File f : files) {
//instead of "V:\Selenium\Scripts\bin\package\classname.class"
//I just end up with "package.classname"
classNames.add(extractClassNameFromPath(f.getPath()));
}
So at this point, I'm able to get a String list of all my class names, and I can put any of them into the classes.add(new XmlClass("package.classname"));
line, allowing me run any of our test classes programmatically. Great!
With all that said, here is the problem I'm facing now: The classes have different @Test methods. By launching just the class, all of the @Test methods will be executed. I want to be able to extract the available @Test methods in that class and present them to the user so they can choose which ones they want.
I have no idea how to extract the @Test methods from our test classes.
Upvotes: 1
Views: 3326
Reputation: 5740
You can use reflections library and its MethodAnnotationsScanner:
Reflections reflections = new Reflections("my.package");
Set<Method> resources =
reflections.getMethodsAnnotatedWith(org.testng.Test.class);
Upvotes: 4