簡體   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