TestNG的@DataProvider应用
先说遇到的问题:
- 将数据驱动方法和测试方法写在了两个类中,运行测试方法会被Skip。
错误代码如下
public class DataTest {
@Test(dataProvider = "range-provider")
public void testIsBetween(int n, int lower,int upper, boolean expected)
{
System.out.println("Received " + n + " " + lower + "-"+ upper + " expected: " + expected);
}
}
public class DataProviders {
@DataProvider(name = "range-provider")
public static Object[][] rangeData() {
int lower = 5;
int upper = 10;
return new Object[][] {
{ lower-1, lower, upper, false },
{ lower, lower, upper, true },
{ lower+1, lower, upper, true },
{ upper, lower, upper, true},
{ upper+1, lower, upper, false },
};
}
}
错误原因: 代码中没有指定在哪个类中找数据,在当前类中也找不到这个dataProvider,所以就认为没有测试数据,直接skip了
以下是官方解释:
A @Test method specifies its Data Provider with the dataProvider attribute. This name must correspond to a method on the same class annotated with @DataProvider(name="…") with a matching name.
By default, the data provider will be looked for in the current test class or one of its base classes. If you want to put your data provider in a different class, it needs to be a static method or a class with a non-arg constructor, and you specify the class where it can be found in the dataProviderClass attribute.
根据官方文档,现在有三种方式来解决我们的问题
1、在父类中写dataProvider,然后在子类中引用
2、在同一个类中写dataProvider和测试方法
3、写在非继承关系的两个类中,需要在@DataProvider中指定dataProviderClass,将其指定你写dataProvider的那个类