是否可以通过testng.xml在TestNG中设置注释?

时间:2012-06-21 13:55:07

标签: java testng dataprovider

我正在使用精彩的TestNG-Framework进行测试。我的问题是,是否可以在testng.xml配置文件中为@ Test-annotation设置注释? 我不想硬编码@ Test-annotation像

@Test(dataProvider = "dataFileProvider", dataProviderClass = TestDataProvider.class)

我想在testng.xml中配置它

3 个答案:

答案 0 :(得分:0)

我对这个案子有两个想法:

工作手册1:StaticProvider

如果需要,您可以轻松更改静态提供程序

工作手册2:Annotation Transformer

从未尝试过,但即使必须手动获取XML数据也应该有效

期待Beust先生的回答......;)

答案 1 :(得分:0)

简短的回答是:不,您无法在testng.xml的代码中添加注释。

您可以使用Annotation Transformer修改现有注释,如Frank所述。

答案 2 :(得分:0)

有时候,你真的想要做某些事情而你却不能,比如访问私有变量以修复内存泄漏。尽管事实上你不能很有趣,但要弄清楚如何做这样的事情。如果您真的想要,我可能会建议尝试使用TestNG对象运行您的套件,然后再运行加载testng.xml文件。

就个人而言,我喜欢使用'mvn test'而且不幸的是,添加pom.xml代码以从testng xml文件运行将要求您提供testng.xml文件,因此'mvn test'将无效。始终确保95%的程序员使用工作,然后允许覆盖。

因此,我可能会建议您自己扩展testng.xml文件并编写一些代码来读取testng.xml文件并使用注释转换器类配置注释。

以下是一些可以帮助您入门的代码:

public class TestNGSuite {
public static void main(String[] args) {
    System.out.println("main start");
    try {
        new TestNGSuite(new Class[]{ Demo.class });
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.out.println("main finish");
}

public TestNGSuite(Class[] classes) throws Exception {
    // Create Suite List
    List<XmlSuite> suites = new ArrayList<XmlSuite>();

    // Add Suite to Suite List
    XmlSuite suite = new XmlSuite();
    suites.add(suite);
    suite.setName("MyTestSuite");

    // Add Test to Suite
    XmlTest test = new XmlTest(suite);
    test.setName("MyTest");

    // Add Class List to Test
    List<XmlClass> xmlClasses = new ArrayList<XmlClass>();
    test.setXmlClasses(xmlClasses);

    // Add Class to Class List
    for(Class clazz: classes) {
        XmlClass xmlClass = new XmlClass(clazz);
        xmlClasses.add(xmlClass);
    }

    // Run TestNG
    TestNG testNG = new TestNG();
    testNG.setXmlSuites(suites);
    testNG.addListener(new TestNGAnnotationTransformer(methodName));
    testNG.addListener(new TestNGSuiteConsoleLogger());
    testNG.run();

    if(testNG.hasFailure()) { // Throw an exception to make mvn goal fail
        throw new Exception("Failed Tests");
    }
}

public static class TestNGSuiteConsoleLogger extends TestListenerAdapter{
      @Override
      public void onTestFailure(ITestResult tr) {
        Console.log(TestNGSuiteConsoleLogger.class, "FAILURE:"+tr.getMethod());
        tr.getThrowable().printStackTrace();
      }
}

public static class TestNGAnnotationTransformer implements IAnnotationTransformer{
      String methodToRun;
      public TestNGAnnotationTransformer(String methodName) {
              methodToRun = methodName;
      }
    public void transform(ITestAnnotation annotation, Class arg1,
            Constructor arg2, Method testMethod) {
            if (methodToRun.equals(testMethod.getName())) {
            annotation.setEnabled(true);
            }
      }
}
}

如果你想运行Demo.class,请确保有一个方法,其中包含TestNG注释“@Test”。