可以将参数传递给TestNG DataProvider吗? [英] Possible to pass parameters to TestNG DataProvider?

查看:108
本文介绍了可以将参数传递给TestNG DataProvider吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们希望针对一组数据值运行某些测试,以验证每个条件都适用。目前,数据存储在平面文件中或简单的Excel电子表格中。

We would like to run some of our tests each against a set of data values, verifying that the same conditions hold true for each. The data is currently stored in either flat files or in simple Excel spreadsheets.

我的第一个想法是创建一个TestNG DataProvider,它将从文件中加载数据并使用为每个数据值调用一次测试方法。我的问题是,不同的测试需要从不同的文件加载数据,并且似乎没有任何方法可以将参数发送到DataProvider。 有人知道这是否可行吗?

My first thought was to create a TestNG DataProvider that would load the data from the file and be used to call the test method once for each data value. My problem is that different tests need to load data from different files and there doesn't appear to be any way to send a parameter to the DataProvider. Does anyone know if this is possible?

理想情况下,我希望代码看起来像下面的示例(简化示例):

Ideally, I would like my code to look like the following (simplified example):

public class OddTest {
    @DataProvider(name = "excelLoader")
    public Iterator<Object[]> loadExcelData(String fileName) {
        ...
    }

    @Test(dataProvider = "excelLoader" dataProviderParameters = { "data.xls" })
    public void checkIsOddWorks(int num)
        assertTrue(isOdd(num));
    }
}


推荐答案

来自 TestNG文档

如果您声明@DataProvider以 java.lang.reflect.Method 作为第一个参数,则TestNG将通过当前测试方法作为第一个参数。当几种测试方法使用相同的@DataProvider并且您希望它根据为其提供数据的测试方法返回不同的值时,此功能特别有用。

If you declare your @DataProvider as taking a java.lang.reflect.Method as first parameter, TestNG will pass the current test method for this first parameter. This is particularly useful when several test methods use the same @DataProvider and you want it to return different values depending on which test method it is supplying data for.

以下代码在其@DataProvider中打印测试方法的名称:

For example, the following code prints the name of the test method inside its @DataProvider:

@DataProvider(name = "dp")
public Object[][] createData(Method m) {
  System.out.println(m.getName());  // print test method name
  return new Object[][] { new Object[] { "Cedric" }};
}

@Test(dataProvider = "dp")
  public void test1(String s) {
}

@Test(dataProvider = "dp")
  public void test2(String s) {
}

,因此将显示:

test1
test2

这也可以与desolat提供的解决方案结合起来,从上下文和方法中确定数据:

This can also be combined with the solution provided by desolat to determine data from the context and the method accordingly:

    @DataProvider(name = "dp")
    public Object[][] foodp(ITestContext ctx, Method method) {
        // ...
    }

这篇关于可以将参数传递给TestNG DataProvider吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆