繁体   English   中英

使用Ant和Junit执行单个测试方法

[英]Execute a single Test Method with Ant and Junit

我正在寻找一种以Jenkins兼容方式运行单一Junit测试方法(而不是整个测试,只是通过“ -D”参数提供给ant的单个测试)的方法。 有很多不同的教程(大多数教程朝完全不同的方向发展),我找不到真正与Junit4。*配合使用的教程。 (例如,不再有TestCase(String methodName)构造函数...)

我可以通过ant使用“ -D”选项解析参数,并且可以使用以下命令启动单个测试用例

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

但是可能由于我通常在TestSuites中运行所有程序,因此Jenkins单独运行单个测试,但不注册已运行的测试。

tl; dr:是否有一种很好的方法可以使用junit运行单个测试方法(而不是整个类),以便Jenkins可以正确获取结果?

该代码不会生成Jenkin的junit插件通常用于发布结果的xml结果文件。 可以使用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();

在这里,您将找到其他使用类似方法的答案。

在本地测试它,它应该生成一个带有结果的xml文件。

现在,在您的Jenkins工作中,您需要添加构建后操作,并使用适当的正则表达式(类似于**/TEST-*.xml类的东西) Publish junit results以捕获结果。

经过一番尝试之后,我们使用反射找到了一个可以正常工作的解决方案:在Junit suite()-方法中:

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);
        }
    }

为此,每个Testclass都需要扩展junit.framework.TestCase

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM