Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to automatically generate JUnit results in xml?

Tags:

java

junit

xml

I am currently writing a series of tests in JUnit. I need to automatically export the results as XML. I was reading that the best way of doing this is by extending the RunListener class and writing the XML that way. Below is a sample of what I have done so far, but I am struggling with how to extract information on each test that has been run. The 'Description' class doesn't seem to have any useful get methods and I feel like I am maybe going about this the wrong way.

Can someone assist with how to get useful information from description (eg. test passed / failed, duration of test, test name etc) or give me some advice on what I actually should be doing?

public class XmlListener extends RunListener {

    private final PrintStream fWriter;

    public XmlListener(JUnitSystem system) {
        this(system.out());
    }

    public XmlListener(PrintStream writer) {
        this.fWriter = writer;
    }

    @Override
    public void testRunStarted(Description description) {
        fWriter.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
    }

    @Override
    public void testRunFinished(Result result) {
        fWriter.append("\t\t</suite>\n");
        fWriter.append("\t</suites>\n");
        fWriter.append("</result>\n");
        printHeader(result.getRunTime());
        printFailures(result);
        printFooter(result);

    }

    @Override
    public void testStarted(Description description) {
        fWriter.append("\t\t\t<case>\n");
        fWriter.append("\t\t\t\t<timestamp>"  + "</timestamp>\n");
        fWriter.append("\t\t\t\t<className>"  + "</className>\n");
        fWriter.append("\t\t\t\t<testName>"  + "</testName>\n");
    }

    @Override
    public void testFinished(Description description) {
        fWriter.append("\t\t\t\t<duration>"  + "</duration>\n");
        fWriter.append("\t\t\t</case>\n");
        Iterator it = description.getAnnotations().iterator();
        while (it.hasNext()) {
            fWriter.append(it.next().toString());
        }
    }

    @Override
    public void testFailure(Failure failure) {
        fWriter.append('E');
    }

    @Override
    public void testIgnored(Description description) {
        fWriter.append('I');
    }

    /**
     * private methods
     * @return
     */

    private PrintStream getWriter() {
        return fWriter;
    }

    protected void printHeader(long runTime) {
        getWriter().println();
        getWriter().println("Time: " + elapsedTimeAsString(runTime));
    }

    protected void printFailures(Result result) {
        List<Failure> failures= result.getFailures();
        if (failures.size() == 0)
            return;
        if (failures.size() == 1)
            getWriter().println("There was " + failures.size() + " failure:");
        else
            getWriter().println("There were " + failures.size() + " failures:");
        int i= 1;
        for (Failure each : failures)
            printFailure(each, "" + i++);
    }

    protected void printFailure(Failure each, String prefix) {
        getWriter().println(prefix + ") " + each.getTestHeader());
        getWriter().print(each.getTrace());
    }

    protected void printFooter(Result result) {
        if (result.wasSuccessful()) {
            getWriter().println();
            getWriter().println("\t</suites>\n");
            getWriter().println("</result>\n");
            getWriter().println(" (" + result.getRunCount() + " test" + (result.getRunCount() == 1 ? "" : "s") + ")");

        } else {
            getWriter().println();
            getWriter().println("FAILURES!!!");
            getWriter().println("Tests run: " + result.getRunCount() + ",  Failures: " + result.getFailureCount());
        }
        getWriter().println();
    }

    /**
     * Returns the formatted string of the elapsed time. Duplicated from
     * BaseTestRunner. Fix it.
     */
    protected String elapsedTimeAsString(long runTime) {
        return NumberFormat.getInstance().format((double) runTime / 1000);
    }
}

UPDATE - Ant build file

<?xml version="1.0" encoding="UTF-8"?>
<project name="COTPlus" default="main" basedir=".">
<property name="src.dir" location="src" />

<target name="test" >
<junit printsummary="on" haltonfailure="false">
  <formatter type="xml" />
  <batchtest todir="/test-reports">
    <fileset dir="${src.dir}" includes="**/ExampleTest.java"  />
  </batchtest>
</junit>
</target>

<target name="main" depends="test">
        <description>Main target</description>
        <echo>${src.dir}</echo>
    </target>

</project>
like image 994
BON Avatar asked Mar 05 '12 14:03

BON


People also ask

How do I run a JUnit test from XML?

Create JUnit Test Case Class java in /work/testng/src. To execute the JUnit test cases, define the property junit="true" as in the xml above. The JUnit test case class TestJunit is defined in class name. For JUnit 4, TestNG will use the org.

What is a JUnit XML?

JUnit xml is a framework that was used in many applications in the test frameworks. By default, the test will generate xml files which are simple reports used for the execution of the test. These files are used to generate the report which was custom, we can also generate the reports as per the requirement of testing.

Can we generate report using JUnit?

By default, JUnit tests generate simple report XML files for its test execution. These XML files can then be used to generate any custom reports as per the testing requirement. We can also generate HTML reports using the XML files.


1 Answers

You can use a Ant Script to get XML Results

<target name="test" >

 <javac srcdir="/src"
     destdir="/bin"
     classpath="/lib/junit.jar"  />


<junit haltonfailure="false">
  <formatter type="xml" />
  <batchtest todir="/test-reports">
    <fileset dir="/bin" includes="tests/ExampleTest.class"  />
  </batchtest>
</junit>
</target>

this will Generate an xml into the /test-reports Folder. More Details on Ant Builds http://ant.apache.org/manual/tasksoverview.html

like image 112
outofBounds Avatar answered Sep 20 '22 13:09

outofBounds