问题描述
我想多次运行测试方法,并且在每次测试运行期间,我希望使用 RestApiCall.sendRequest() 方法的不同参数运行初始化方法,例如 a、b、c 和 d。我还希望测试方法根据传递的参数打印测试名称。
@BeforeaClass
void initialise(){
ResponseData responsedata = RestApi.sendRequest("a");
}
@Test
void TestApiCall(){
testResponse(responsedata);
System.out.println("Passed TestApiCall A");
}
解决方法
有两种方法可以做到这一点。
方法 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
方法的参数并在其中进行 rest 调用初始化。
这是一个示例,展示了这一点
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"},{"c"}
};
}
}
我还希望测试方法根据参数打印测试名称 通过。
您可以让您的测试类实现 org.testng.ITest
接口并让它返回一个自定义名称,但这一切都归结为您正在使用的实际报告器,以及它是否尊重这一点。如果您只实现自己的 org.testng.IReporter
,您可以根据需要进行自定义