I want to create test reports generated by JUnit / TestNG PROGRAMMATICALLY. So, that rules out ANT. My main concern is to generate XML files which are created by Junit while executing test cases. I'have read that RunListener could help me achieve that, but i havn't been able to figure out how ? I'm using Selenium to created my test cases.
How can i generate XML files which are created by JUnit ?
JUnit does not generate XML reports. There isn't a standard XML output format for JUnit.
Other tools generate XML, such as Ant/Maven. So the first thing you need to do is to decide which form of XML file you want, as in what you want to do with the files once you've created them.
And, actually, your restriction of programmatically doesn't rule out ANT. You can invoke ant programmatically (see Invoke ant from java, then return to java after ant termination). This would probably be the easiest way to generate files which are ant-compatible.
If you wish to create your own XML files, then you can create a class which extends RunListener, and then run your tests by invoking JUnitCore#run(), or similar.
public void main(String... args) {
JUnitCore core= new JUnitCore();
core.addListener(new RingingListener());
core.run(MyTestClass.class);
}
Your RunListener would just emit the appropriate XML. It is fairly easy to understand: override the methods testRunStarted() etc and write out the XML. For an example of how it works, see TextListener, which does the same thing, but for text.
xml files are generated by ant-junit, and we can do that by program, the code will look like next :
Project project = new Project();
JUnitTask task = new JUnitTask();
project.setProperty("java.io.tmpdir",String); //set temporary directory
task.setProject(project);
JUnitTask.SummaryAttribute sa = new JUnitTask.SummaryAttribute();
sa.setValue("withOutAndErr");
task.setFork(false);
task.setPrintsummary(sa);
FormatterElement formater = new FormatterElement();
FormatterElement.TypeAttribute type = new FormatterElement.TypeAttribute();
type.setValue("xml");
formater.setType(type);
task.addFormatter(formater);
JUnitTest test = new JUnitTest(String);// set Test.class.getname()
test.setTodir(File); // set Location for your report
task.addTest(test);
task.execute();
You asked nearly the same
here
If you look at the TestNG doc you can use :
The org.testng.IReporter interface which only has one method:
public void generateReport(List suites, String outputDirectory)
This method will be invoked by TestNG when all the suites have been run and you can inspect its parameters to access all the information on the run that was just completed.