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