TestNG同时使用DataProvider和Parameters

本文介绍了如何在TestNG测试方法中同时使用@DataProvider和@Parameters,通过ITestContext来实现这一功能。在某些场景下,如根据参数选择不同测试数据或执行不同逻辑,这种混用变得必要。尽管TestNG本身不直接支持,但可以通过ITestContext获取配置参数,并在@DataProvider和@Test方法中结合使用。示例代码和完整Demo项目展示了如何从Excel文件读取数据并根据配置参数执行相应的测试。
摘要由CSDN通过智能技术生成

TestNG @Test测试方法中同时使用DataProvider和Parameters

实践中经常会遇到需要在@Test方法中混合使用TestNG的@DataProvider和@Parameters的情形,比如,

  • 根据参数的不同使用不同的测试数据
  • 根据参数的不同执行不同的测试逻辑
  • 测试数据含有大量的相同字段,为了提高效率

TestNG @Test方法本身不提供这样的语法(到目前为止最新的版本TestNG 6.9.4都没有这样的功能),使用时只能在annotation中指定@Dataprovider或者@Parameters,而不能两者同时指定。

其实这个问题很好解决,秘诀就在ITestContext,ITestContext 是TestNG 测试的上下文,它里面包含很多信息,包括我们定义在TestNG配置文件中的参数,下面是ITestContext的Java doc,

public interface ITestContext
extends IAttributes
This class defines a test context which contains all the information for a given test run. An instance of this context is passed to the test listeners so they can query information about their environment.

使用ITestContex获取参数的方法如下,

public void runTest(ITestContext context ,String id, String name, String input, String expectedValue) {
String testId = context.getCurrentXmlTest().getParameter("test_id");

ITestContext可以用在@Before, @Test, @DataProvider中。下面是TestNG官方文档中关于ITesetContext使用的信息。

5.18.1 - Native dependency injection

TestNG lets you declare additional parameters in your methods. When this happens, TestNG will automatically fill these parameters with the right value. Dependency injection can be used in the following places:
Any @Before method or @Test method can declare a parameter of type ITestContext.
Any @AfterMethod method can declare a parameter of type ITestResult, which will reflect the result of the test method that was just run.
Any @Before and @After methods can declare a parameter of type XmlTest, which contain the current tag.
Any @BeforeMethod (and @AfterMethod) can declare a parameter of type java.lang.reflect.Method. This parameter will receive the test method that

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值