之前说过@Factory更适合于同一类型的参数变化性的测试,那么如果参数值没有特定的规律时,我们可以采用@Factory和@DataProvider相结合的方式进行测试
注意要点:请注意测试方法将被一共执行的次数,因为@Factory本身就属于循环测试的类型,@DataProvider也是属于测试整体循环的类型
Java code:
/** * * <p> * Title: TestngFactoryDataProvider * </p> * * <p> * 配置文件:testng-factoryDataProvider.xml * * Description: * 使用@DataProvider作为数据注入的方式,向Factory中注入数据,并执行测试,被执行的测试类:TestngFactoryTest * </p> * * <p> * Company: * </p> * * @author : Dragon * * @date : 2014年10月22日 */ public class TestngFactoryDataProvider { @Factory(dataProvider = "datasource") public Object[] createInstances(int a) { System.out.println(a); Object[] result = new Object[a]; for (int i = 0; i < a; i++) { result[i] = new TestngFactoryTest(i * 10); } return result; } @DataProvider(name = "datasource") public Object[][] getDatasource() { return new Object[][] { new Object[] { 2 }, new Object[] { 4 } }; } }
public class TestngFactoryTest { private int m_numberOfTimes; public TestngFactoryTest(int numberOfTimes) { this.m_numberOfTimes = numberOfTimes; } private static int num; @Test public void testServer() { num++; System.out.println("num " + num + " m_numberOfTimes :" + m_numberOfTimes); } }
配置文件:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd"> <!-- allow-return-values 默认值为FALSE,表示返回值将被忽略 --> <suite name="framework_testng" allow-return-values="true"> <test verbose="2" name="TestMethods"> <classes> <class name="com.dragon.testng.annotation.TestngFactoryDataProvider"> </class> </classes> </test> </suite>
测试结果:
num 1 m_numberOfTimes :20 num 2 m_numberOfTimes :10 num 3 m_numberOfTimes :0 num 4 m_numberOfTimes :30 num 5 m_numberOfTimes :10 num 6 m_numberOfTimes :0 PASSED: testServer PASSED: testServer PASSED: testServer PASSED: testServer PASSED: testServer PASSED: testServer =============================================== TestMethods Tests run: 6, Failures: 0, Skips: 0 ===============================================
如果我厚道,
别认为我笨拙。因为我明白,
厚德能载物,助人能快乐。