@DataProvider ITestContext 参数

本文介绍了如何在TestNG框架中利用ITestContext数据提供者来动态生成测试数据,根据不同测试组的需求返回不同数量的随机整数数组,实现了灵活的数据驱动测试策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 1 package roger.testng;
 2 
 3 import java.util.Random;
 4 
 5 import org.testng.ITestContext;
 6 import org.testng.annotations.DataProvider;
 7 import org.testng.annotations.Test;
 8 
 9 /*
10  *  数据提供者在方法签名中声明了一个 ITestContext 类型的参数
11  *  testng 会将当前的测试上下文设置给它
12  *  
13  */
14 public class TestDataProviderITestContext {
15     @DataProvider
16     public Object[][] randomIntegers(ITestContext context) {
17         String[] groups= context.getIncludedGroups();
18         int size = 2;
19         for (String group : groups) {
20             System.out.println("--------------" + group);
21             if (group.equals("function-test")) {
22                 size = 10;
23                 break;
24             }
25         }
26         
27         Object[][] result = new Object[size][];
28         Random r = new Random();
29         for (int i = 0; i < size; i++) {
30             result[i] = new Object[] {new Integer(r.nextInt())};
31         }
32         
33         return result;
34     }
35     
36     // 如果在 unite-test 组中执行, 将返回2个随机整数构成数组;
37     // 如果在 function-test 组中执行, 将返回 10 个随机整数构成数组
38     @Test(dataProvider = "randomIntegers", groups = {"unit-test", "function-test"})
39     public void random(Integer n) {
40         System.out.println(n);
41     }
42     
43 }

通过 testng.xml 指定运行 unite-test 组还是 function-test 组。

转载于:https://www.cnblogs.com/Roger1227/p/3851159.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值