java - 仅使用注释使用不同的测试数据运行测试方法多次
问题描述
我想多次运行测试方法,并且在每次测试运行期间,我希望初始化方法使用 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
方法的参数并在其中进行其余调用初始化。
这是一个示例,它显示了实际情况
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
您可以根据需要进行此自定义
推荐阅读
- python - 如何在 Python 中使用 praw 将保存的 reddit 帖子列表抓取到 txt 文件
- python - 如何获取“src=...”的 url?
- machine-learning - 当我们在 PyTorch 张量上调用 cpu().data.numpy() 时会发生什么?
- android - 为什么我不能将数据放入 Firestore?
- powerbi - 使用 DAX 查找 MAX 7 天平均值
- xcode - 视图中缺少设备:在情节提要中
- android - 如何在 service worker 中播放声音甚至在 chrome 中振动?
- java - 如何在另一个布局中嵌入布局?
- javascript - 使用 React 开发的 Chrome 扩展不渲染
- typescript - 用于描述 API 响应的接口应该包含所有字段还是只包含应用程序实际需要的字段?