前面写过一个无参的数据提供者方法,还有三种有参数据提供者方法。
一、Method表示当前测试的方法
Dataprovidertest.java代码
package com.tzf.testng; import java.lang.reflect.Method; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class DataProviderTest { @DataProvider public Object[][] providerMethod(Method method){ Object[][] result = null; if(method.getName().equals("testmethod1")){ result = new Object[][]{new Object[]{1}}; }else if(method.getName().equals("testmethod2")){ result = new Object[][]{new Object[]{2}}; }else{ result = new Object[][]{new Object[]{3}}; } return result; } @Test(dataProvider="providerMethod") public void testmethod1(int param){ System.out.println("method1 received:"+param); } @Test(dataProvider="providerMethod") public void testmethod2(int param){ System.out.println("method2 received:"+param); } @Test(dataProvider="providerMethod") public void testmethod3(int param){ System.out.println("method3 received:"+param); } }
注意这里我的Dataprovider的name值没有指定,默认用的是方法名。 Testng.xml代码
<?xml version="1.0" encoding="UTF-8"?> <suite name="Suite" parallel="false"> <test name="DataProviderTest"> <classes> <class name="com.tzf.testng.DataProviderTest" /> </classes> </test> </suite>
运行结果代码
RemoteTestNG starting method1 received:1 method2 received:2 method3 received:3 RemoteTestNG finishing: 145 ms
二、ITestContent当前测试的上下文信息
Dataprovidertest2.java代码
package com.tzf.testng; import java.util.Random; import org.testng.ITestContext; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class DataProviderTest2 { @DataProvider public Object[][] providerMethod(ITestContext context){ String[] groups = context.getIncludedGroups(); int size = 2; for(String group : groups){ if(group.equals("function-test")){ size = 10 ; break; } } Object[][] result = new Object[size][]; Random r = new Random(); for(int i=0;i<size;i++){ result[i] = new Object[]{new Integer(r.nextInt())}; } return result; } @Test(dataProvider="providerMethod",groups={"function-test","unit-test"}) public void testmethod1(Integer n){ System.out.println("method1 received:"+n); } }
Testng.xml代码
<?xml version="1.0" encoding="UTF-8"?> <suite name="Suite" parallel="false"> <test name="DataProviderTest2"> <groups> <run> <include name="function-test"/> <exclude name="unit-test"/> </run> </groups> <classes> <class name="com.tzf.testng.DataProviderTest2" group="function-test"/> </classes> </test> </suite>
运行结果代码
RemoteTestNG starting method1 received:-1987654923 method1 received:338477914 method1 received:1910366338 method1 received:107205369 method1 received:-1018164959 method1 received:-2060129321 method1 received:-803464435 method1 received:-814156781 method1 received:-1075504680 method1 received:-774924512 RemoteTestNG finishing: 151 ms