以编程方式运行TestNG,获取“无法在类路径中找到类”异常

时间:2016-03-20 14:12:03

标签: java classpath testng

我正在尝试使用虚拟XML以编程方式运行TestNG,如下所述: http://testng.org/doc/documentation-main.html#running-testng-programmatically

这是我的代码:

        TestListenerAdapter tla = new TestListenerAdapter();
        TestNG tng = new TestNG();
        tng.addListener(tla);

        XmlSuite suite = new XmlSuite();
        suite.setName("Retry Suite");

        for (ITestResult testResult : failedTests){
            XmlTest xmlTest = new XmlTest(suite);
            //xmlTest.setSuite(suite);
            xmlTest.setName(testResult.getTestName());

            List<XmlClass> xmlClasses = new ArrayList<>();
            xmlClasses.add(new XmlClass(testResult.getTestClass().getXmlClass().toString()));
            xmlTest.setXmlClasses(xmlClasses);

            xmlTest.getClasses().addAll(xmlClasses);
            suite.addTest(xmlTest);
        }

        List<XmlSuite> suites = new ArrayList<>();
        suites.add(suite);
        tng.setXmlSuites(suites);
        tng.run();

当代码到达块时,我得到以下异常:

[ERROR] org.testng.TestNGException:
[ERROR] Cannot find class in classpath: [XmlClass class=tests.system.browserTests.BrowserTests]
[ERROR] at org.testng.xml.XmlClass.loadClass(XmlClass.java:81)
[ERROR] at org.testng.xml.XmlClass.init(XmlClass.java:73)
[ERROR] at org.testng.xml.XmlClass.init(XmlClass.java:63)
[ERROR] at org.testng.xml.XmlClass.<init>(XmlClass.java:39)
[ERROR] at tests.utils.autoReport.postHandler.TestNGLiseteners.retrySuiteVirtXml(TestNGLiseteners.java:226)
[ERROR] at tests.utils.autoReport.postHandler.TestNGLiseteners.onExecutionFinish(TestNGLiseteners.java:204)

我无法弄清楚为什么?有什么想法吗?

2 个答案:

答案 0 :(得分:4)

您似乎没有在此行中正确实例化XmlClass

new XmlClass(testResult.getTestClass().getXmlClass().toString())

改为使用

new XmlClass(testResult.getTestClass().getName())

答案 1 :(得分:0)

确保您的.project文件至少包含:

</projects>
    <buildSpec>
        <buildCommand>
            <name>org.eclipse.jdt.core.javabuilder</name>
            <arguments>
            </arguments>
        </buildCommand>
    </buildSpec>
    <natures>
        <nature>org.eclipse.jdt.core.javanature</nature>
    </natures>

默认情况下,还要检查输出目录中已编译类的可用性/bin

PS。对于标准java项目