java - Testng - 使用 setTestClasses() 传递参数

标签 java class parameters testng

我正在使用编程方法来运行 Courier 类中包含的测试。

TestListenerAdapter tla = new TestListenerAdapter();
TestNG testng = new TestNG();
testng.setTestClasses(new Class[] { Courier.class });
testng.addListener(tla);
testng.run();

如何将参数传递给包含在此类中的测试? 例如

testng.setTestClasses(new Class[] { Courier("parameter").class });

express :

public class Courier {
@Parameter(passed parameter)
@Test
public void Courier_Test(String parameter){
    System.out.println(parameter);
}   

感谢您的帮助!

最佳答案

几个想法:

即使您以编程方式运行测试,您也应该能够在 testng.xml 文件上调用 TestNG。像这样向文件添加参数(来自 documentation ):

<suite name="My suite">
   <parameter name="parameter"  value="Foo"/>
   <test name="Courier Test" />
   < ... >

如果出于某种原因您没有使用 testng.xml 文件,您可以使用 DataProvider,作为测试类中的方法或作为静态类,具体取决于您需要做什么。下面的示例(也来自 documentation )。

类内的DataProvider:

//This method will provide data to any test method that declares
//that its Data Provider is named "test1"
@DataProvider(name = "test1")
public Object[][] createData1() {
   return new Object[][] {
     new Object[] { "Parameter" }
   }
}

//This test method declares that its data should be supplied 
//by the Data Providernamed "test1"
@Test(dataProvider = "test1")
public void Courier_Test(String parameter) {
 System.out.println(parameter);
} 

外部类中的DataProvider:

public static class StaticProvider {
  @DataProvider(name = "create")
  public static Object[][] createData() {
    return new Object[][] {
      new Object[] { "Parameter" }
    }
  }
}

public class Courier {
  @Test(dataProvider = "create", dataProviderClass = StaticProvider.class)
  public void Courier_Test(String parameter) {
    // ...
  }
}

关于java - Testng - 使用 setTestClasses() 传递参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5407350/

相关文章:

xml - Delphi 由于枚举名称中的连字符导致错误导入 WSDL,我该怎么办?

jquery - 添加类事件 jQuery

c# - 如何像查询一样参数化mysql?

configuration - 如何使用 weblogic 10.3.x 在 web.xml 中动态传递参数?

java - 如何使用 java 应用程序发出 Elastic search url 请求?

java - 在 Java 中使用 DocumentTraversal 递归遍历 XML 元素

java - Pom.xml OpenHAB 中的生命周期配置未涵盖插件执行

java - Spring bean 范围为 "one object per test method"

java - 重用从类返回的用户输入值,而不重新请求用户输入

ruby - Sinatra 的多个 block 参数