@Factory和@DataProvider的区别

  1. DataProvider: A test method that uses DataProvider will be executed a multiple number of times based on the data provided by the DataProvider. The test method will be executed using the same instance of the test class to which the test method belongs.
  2. Factory: A factory will execute all the test methods present inside a test class using a separate instance of the respective class

也就是说,在DataProvider中测试方法将使用相同的实例执行测试类中的测试方法。   

在Factory中将执行所有测试方法,使用一个单独的各自的类的实例,将动态的创建类的实例,你可以多次运行测试类。

举个例子比较好区分:对于登录到一个网站的测试,如果你想运行这个测试类多次,登入网站,那么可以使用Factory来动态创建测试类来测试。如果你想要根据不同的用户名和密码来登录网站那么就可以使用DataProvider,每一次的登录都使用不同的登录数据。

使用DataProvider:

public class DataProviderClass
{
    @BeforeClass
    public void beforeClass() {
        System.out.println("Before class executed");
    }
 
    @Test(dataProvider = "dataMethod")
    public void testMethod(String param) {
        System.out.println("The parameter value is: " + param);
    }
 
    @DataProvider
    public Object[][] dataMethod() {
        return new Object[][] { { "one" }, { "two" } };
    }
}

  结果:

Before class executed
The parameter value is: one
The parameter value is: two
PASSED: testMethod("one")
PASSED: testMethod("two")

  说明:不同的数据,但是使用的测试类是相同的,beforeclass只被执行了一次,说明只创建了一个测试类实例。

使用Factory:

public class SimpleTest
{
    private String param = "";
 
    public SimpleTest(String param) {
        this.param = param;
    }
 
    @BeforeClass
    public void beforeClass() {
        System.out.println("Before SimpleTest class executed.");
    }
 
    @Test
    public void testMethod() {
        System.out.println("testMethod parameter value is: " + param);
    }
}
 
public class SimpleTestFactory
{
    @Factory
    public Object[] factoryMethod() {
        return new Object[] {
                                new SimpleTest("one"),
                                new SimpleTest("two")
                            };
    }
}

  结果:

Before SimpleTest class executed.
testMethod parameter value is: two
Before SimpleTest class executed.
testMethod parameter value is: one
PASSED: testMethod
PASSED: testMethod

  说明:beforeClass在每一个测试方法之前都执行了,为每一个测试都生成了一个测试的实例。

这个就是他们之间的区别。

posted @ 2015-05-31 14:48  silenceer  阅读(1013)  评论(1编辑  收藏  举报