您的位置:软件测试 > 开源软件测试 > 开源单元测试工具 > TestNG
TestNG的@Factory及其与@DataProvider的区别
作者:网络转载 发布时间:[ 2016/6/28 11:45:22 ] 推荐标签:单元测试工具 软件测试

  因此,如果想要使用不同的测试数据执行一个测试用例多次,那么采用DataProvider;如果想要多次执行一个测试类的所有用例,那么采用Factory。
  当然,Factory与DataProvider也可结合在一起使用,请看下面例子:
  在测试类Test1中有2个用例,其中用例test2通过dataProvider提供参数,而在DataProvider中提供了3组参数,因此测试类Test1每次会执行4个用例;
  在工厂类FactoryWithDataprovider中,通过DataProvider为工厂方法提供参数,因此工厂方法会创建2个Test1的实例。
1 public class Test1 {
2     private String name;
3     public Test1(String name) {
4         this.name = name;
5     }
6
7     @Test
8     public void test1() {
9         System.out.println("test1: His name is " + name);
10     }
11
12     @Test(dataProvider = "data1")
13     public void test2(String hobby) {
14         System.out.println("test2: " + name + " likes " + hobby);
15     }
16
17     @DataProvider(name = "data1")
18     public Object[][] createdata() {
19         return new Object[][] {
20             {"baozoumanhua"},
21             {"movie"},
22             {"music"}
23         };
24     }
25 }
26
27 public class FactoryWithDataprovider {
28
29     @DataProvider(name = "data2")
30     public Object[][] createdata() {
31         return new Object[][] {
32             {"wangnima"},
33             {"wangnimei"},
34         };
35     }
36
37     @Factory(dataProvider = "data2")
38     public Object[] createInstace(String name) {
39         return new Object[] {
40             new Test1(name)
41         };
42     }
43 }
  执行结果如下:2个实例,每个实例执行4个用例,总共8个用例。
test1: His name is wangnima
test1: His name is wangnimei
test2: wangnima likes baozoumanhua
test2: wangnima likes movie
test2: wangnima likes music
test2: wangnimei likes baozoumanhua
test2: wangnimei likes movie
test2: wangnimei likes music
PASSED: test1
PASSED: test1
PASSED: test2("baozoumanhua")
PASSED: test2("movie")
PASSED: test2("music")
PASSED: test2("baozoumanhua")
PASSED: test2("movie")
PASSED: test2("music")

上一页12下一页
软件测试工具 | 联系我们 | 投诉建议 | 诚聘英才 | 申请使用列表 | 网站地图
沪ICP备07036474 2003-2017 版权所有 上海泽众软件科技有限公司 Shanghai ZeZhong Software Co.,Ltd