您的位置:軟件測試 > 開源軟件測試 > 開源單元測試工具 > TestNG
TestNG的@Factory及其與@DataProvider的區(qū)別
作者:網(wǎng)絡(luò)轉(zhuǎn)載 發(fā)布時間:[ 2016/6/28 11:45:22 ] 推薦標(biāo)簽:單元測試工具 軟件測試

  因此,如果想要使用不同的測試數(shù)據(jù)執(zhí)行一個測試用例多次,那么采用DataProvider;如果想要多次執(zhí)行一個測試類的所有用例,那么采用Factory。
  當(dāng)然,F(xiàn)actory與DataProvider也可結(jié)合在一起使用,請看下面例子:
  在測試類Test1中有2個用例,其中用例test2通過dataProvider提供參數(shù),而在DataProvider中提供了3組參數(shù),因此測試類Test1每次會執(zhí)行4個用例;
  在工廠類FactoryWithDataprovider中,通過DataProvider為工廠方法提供參數(shù),因此工廠方法會創(chuàng)建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 }
  執(zhí)行結(jié)果如下:2個實例,每個實例執(zhí)行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下一頁
軟件測試工具 | 聯(lián)系我們 | 投訴建議 | 誠聘英才 | 申請使用列表 | 網(wǎng)站地圖
滬ICP備07036474 2003-2017 版權(quán)所有 上海澤眾軟件科技有限公司 Shanghai ZeZhong Software Co.,Ltd