【问题标题】:Execute a single Test Method with Ant and Junit使用 Ant 和 Junit 执行单个测试方法
【发布时间】:2015-05-26 13:38:45
【问题描述】:

我正在寻找一种以符合 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 可以正确获取结果?

【问题讨论】:

    标签: java ant jenkins junit


    【解决方案1】:

    该代码不会生成 Jenkins 的 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();
    

    Here你会找到其他使用类似方法的答案。

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

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

    【讨论】:

    • 感谢您的努力和快速答复!我们发现了我们的问题并且能够正确使用 Junit + Ant + Jenkins。有关更多信息,请参阅我的答案。
    【解决方案2】:

    玩了一会之后,我们找到了一个使用反射的正常工作解决方案: 在 Junit 套件()方法中:

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多