完全有两种方法可以做到这一点。
方法 1:使用数据提供者驱动的工厂
在这里,您有一个@Factory
由数据提供者提供支持的,要创建测试类实例,并且在其中,您可以@BeforeMethod
执行您需要执行的任何休息调用调用,然后让您的@Test
方法与响应一起工作。
这是一个完整的示例,显示了这一点
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Factory;
import org.testng.annotations.Test;
public class SampleTestClassUsingFactory {
private final String parameter;
@Factory(dataProvider = "dp")
public SampleTestClassUsingFactory(String parameter) {
this.parameter = parameter;
}
@BeforeMethod
public void beforeMethod() {
//Include your code to fire your Rest Call here
}
@Test
public void testMethod() {
System.err.println("Using the parameter " + parameter);
}
@DataProvider(name = "dp")
public static Object[][] getTestData() {
return new Object[][]{
{"a"},
{"b"},
{"c"}
};
}
}
方法 2:使用数据提供者驱动的测试方法
在这种情况下,您的@Test
方法由数据提供者提供支持,并在您的内部@BeforeMethod
拦截传递给该@Test
方法的参数并在其中进行其余调用初始化。
这是一个示例,它显示了实际情况
public class SampleTestClassUsingDataProvider {
@BeforeMethod
public void beforeMethod(ITestResult testResult) {
Object[] parameters = testResult.getParameters();
//Simulate as if we are doing something with the parameters array
System.err.println("Parameters for the test method = " + Arrays.toString(parameters));
}
@Test(dataProvider = "dp")
public void testMethod(String parameter) {
System.err.println("Using the parameter " + parameter);
}
@DataProvider(name = "dp")
public static Object[][] getTestData() {
return new Object[][]{
{"a"},
{"b"},
{"c"}
};
}
}
另外我希望测试方法根据传递的参数打印测试名称。
您可以让您的测试类实现该org.testng.ITest
接口并让它返回一个自定义名称,但这一切都归结为您正在使用的实际报告器以及它是否尊重这一点。如果您只是实现自己的,它会很容易,org.testng.IReporter
您可以根据需要进行此自定义