Generate XML Files Used by JUnit Reports Generate XML Files Used by JUnit Reports xml xml

Generate XML Files Used by JUnit Reports


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 directorytask.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 reporttask.addTest(test);         task.execute();


As being mentioned JUnit does not generate reports. But if you use Maven executingmvn clean install test surefire-report:reportwill do the trick

https://examples.javacodegeeks.com/core-java/junit/junit-report-generation-example/