BenSower
BenSower

Reputation: 1612

Execute a single Test Method with Ant and Junit

I am looking for a way to run single Junit test methods (not the whole test, just a single one provided through the "-D" parameter to ant) in a Jenkins compliant way. There are a lot of different tutorials (most of them going into completely different directions) and I could not find one actually working with Junit4.*. (e.g. there is no TestCase(String methodName) constructor anymore...)

I am able to parse parameters with the "-D" option through ant and I can start single testcases with

Request requestCase = Request.method(Class.forName("testmethod"), Parameter.testCase);
Result result = new JUnitCore().run(requestCase);

but probably since I am usually running everything in TestSuites, Jenkins runs the single test seperately but doesn't register the tests have been run.

tl;dr: Is there a good way to run a single test method (not a whole class) with junit, so that Jenkins can properly pick up the results?

Upvotes: 1

Views: 1310

Answers (2)

BenSower
BenSower

Reputation: 1612

After playing around a bit, we found a properly working solution using reflections: In the Junit suite()-method:

if (Parameter.testCase != null){  //Parameter contains all parsed parameters
        try {

            Class<?> classGen = Class.forName("package.path" + Parameter.testPlatform.toString());

            Constructor<?> constructor =
                    classGen.getConstructor( new Class[] { String.class } );

            suite.addTest( (Test) constructor.
                    newInstance( new Object[] { Parameter.testCase } ) );
            return suite;
        }
        catch (ClassNotFoundException e) {
            Logger.log("ERROR: Error executing single test" + Parameter.testCase);
            e.printStackTrace(); //the output is actually logged properly
            System.exit(1);
        }
    }

For this to work, every Testclass needs to extend junit.framework.TestCase

Upvotes: 0

Vitalii Elenhaupt
Vitalii Elenhaupt

Reputation: 7326

That code does not generate xml result file that Jenkin's junit plugin usually use to publish results. It's possible to do that with an AntXmlRunListener

AntXmlRunListener xmlListener = new AntXmlRunListener();
FileOutputStream reportStream = new FileOutputStream(reportDir + "/TEST-" + className + ".xml");
xmlListener.setOutputStream(reportStream);

JUnitCore junit = new JUnitCore();
junit.addListener(xmlListener);

// ...
// junit.run(requestCase);

xmlListener.setOutputStream(null);
reportStream.close();

Here you will find other answers with similar approach used.

Test it locally, it should generate an xml file with result.

Now in your Jenkins job you need to add post build action Publish junit results with an appropriate regexp(something like this **/TEST-*.xml) to capture results.

Upvotes: 1

Related Questions