TestNG--@Factory

原文地址:http://blog.csdn.net/wanghantong

TestNg的@Factory注解从字面意思上来讲就是采用工厂的方法来创建测试数据并配合完成测试

其主要应对的场景是:对于某一个测试用例或方法,我们需要输入多个测试数据进行测试,并且这些测试数据可以是有一定关系(可以通过代码控制),

ps. 其实就是用一个类封装这些测试数据。在默认情况下,testNG调用测试类的无参数构造方法,将测试类实例化,然后执行在每个测试类中的测试方法,如果测试类没有无参数的构造方法,就会报错。使用@Factory可以实现调用有参数的构造函数来创建实例对象。

此时,我们就可以把自动化或者手动测试时的遇到的只因测试数据不同的多个测试用例合并成一个测试用例,来进行更方便和快捷的测试,

对编写自动化测试代码人员节省了很多时间

策略:一般我们会在标有@Factory注解的方法中对测试类进行调用,这时TestNg会自动调用测试类中带有@Test注解的方法

java code:

 

/**
 * 
 * <p>
 * Title: TestngFactory
 * </p>
 * 
 * <p>
 * Description: 配置文件:testng-factory.xml
 * 
 * TestngFactory工厂类,在带有@Factory注解的方法中调用被执行的测试类,TestNg会自动调用被执行类中带有@Test注解的方法,
 * 被执行的测试类为:TestngFactoryTest,
 * </p>
 * 
 * <p>
 * Company:
 * </p>
 * 
 * @author : Dragon
 * 
 * @date : 2014年10月22日
 */
public class TestngFactory {
    @Factory
    public Object[] createInstances() {
        Object[] result = new Object[10];
        for (int i = 0; i < 10; i++) {
            result[i] = new TestngFactoryTest(i * 10);
        }
        return result;
    }
}

 

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);
    }
}

 

配置文件:只需要配置带有@Factory注解的类即可

<?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.TestngFactory">
            </class>
        </classes>
    </test>
</suite>

 

测试结果:

num    1  m_numberOfTimes :30
num    2  m_numberOfTimes :20
num    3  m_numberOfTimes :70
num    4  m_numberOfTimes :60
num    5  m_numberOfTimes :90
num    6  m_numberOfTimes :50
num    7  m_numberOfTimes :10
num    8  m_numberOfTimes :0
num    9  m_numberOfTimes :40
num    10  m_numberOfTimes :80
PASSED: testServer
PASSED: testServer
PASSED: testServer
PASSED: testServer
PASSED: testServer
PASSED: testServer
PASSED: testServer
PASSED: testServer
PASSED: testServer
PASSED: testServer

===============================================
    TestMethods
    Tests run: 10, Failures: 0, Skips: 0
===============================================

 

 
posted @ 2015-08-18 15:48  不将就!  阅读(789)  评论(0编辑  收藏  举报