首页 > 代码库 > TestNg的工厂測试引用@DataProvider数据源----灵活使用工厂測试

TestNg的工厂測试引用@DataProvider数据源----灵活使用工厂測试

之前说过@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
===============================================








假设我厚道,
别觉得我笨拙。

由于我明确,
厚德能载物,助人能快乐。

TestNg的工厂測试引用@DataProvider数据源----灵活使用工厂測试