TestNG測試帶參構(gòu)造函數(shù)的類
今天被同事問到一個(gè)問題,問題描述如下:
一個(gè)測試類,只有一個(gè)帶參構(gòu)造函數(shù)。在帶參構(gòu)造函數(shù)上加@Test,同時(shí)加@Parameters注解從testng.xml中傳遞參數(shù)。為保證測試函數(shù)在帶參構(gòu)造函數(shù)之后執(zhí)行,所以測試方法前的@Test加了dependsOnMethods屬性,依賴于帶參構(gòu)造函數(shù)。
重現(xiàn)問題的示例代碼如下:
package com.ibm.testng.test; import org.testng.annotations.Parameters; import org.testng.annotations.Test; public class WebTest { //Times staying on the server private int stayTime; //Constructor with params @Test @Parameters({"stayTime"}) public WebTest(int stayTime) { System.out.println("Constructor with parameter!"); this.stayTime = stayTime; } @Test(dependsOnMethods="WebTest") public void stayOnServer() { System.out.println("The times staying on server: " + stayTime); } } |
輸出結(jié)果:
根據(jù)輸出結(jié)果可知,錯(cuò)誤原因是沒有找到stayOnServer()依賴的測試函數(shù)WebTest()。可能會(huì)疑問,不是有名稱為WebTest()的函數(shù)嗎,而且還用@Test注解了,為什么會(huì)提示找不到呢?
這個(gè)錯(cuò)誤,跟TestNG的執(zhí)行原理有關(guān)。TestNG啟動(dòng)之后,先調(diào)用構(gòu)造函數(shù)創(chuàng)建所有的測試實(shí)例,然后才進(jìn)行測試。因此,構(gòu)造函數(shù)與測試函數(shù)的執(zhí)行時(shí)機(jī)不一樣,構(gòu)造函數(shù)在所有測試方法之前先執(zhí)行,沒有必要再通過@Test的dependsOnMethods屬性使測試函數(shù)依賴于構(gòu)造函數(shù)。
. 構(gòu)造函數(shù)沒必要用@Test注解(注解了也不會(huì)報(bào)錯(cuò)),但是TestNG不會(huì)把它當(dāng)做測試函數(shù),它也不會(huì)和其他測試函數(shù)一起執(zhí)行。可能習(xí)慣性地認(rèn)為帶參構(gòu)造函數(shù)前的@Parameters一定要和@Test一起使用,其實(shí)不是這樣的,@Parameters可以放的位置有如下兩種情況:
. 構(gòu)造函數(shù)沒必要用@Test注解(注解了也不會(huì)報(bào)錯(cuò)),但是TestNG不會(huì)把它當(dāng)做測試函數(shù),它也不會(huì)和其他測試函數(shù)一起執(zhí)行。可能習(xí)慣性地認(rèn)為帶參構(gòu)造函數(shù)前的@Parameters一定要和@Test一起使用,其實(shí)不是這樣的,@Parameters可以放的位置有如下兩種情況:
1. 任何已經(jīng)被@Test,@Factory或者Configuration annotation(@BeforeXXX/@AfterXXX)注解的函數(shù)。
2. 測試類中至多一個(gè)構(gòu)造函數(shù)前面。TestNG會(huì)調(diào)用該構(gòu)造函數(shù)創(chuàng)建測試實(shí)例,并從testng.xml中獲得該構(gòu)造函數(shù)需要的參數(shù)。
可能你希望使用某個(gè)構(gòu)造函數(shù)來創(chuàng)建測試實(shí)例,但是TestNG會(huì)根據(jù)自己的規(guī)則選擇構(gòu)造函數(shù)。TestNG選擇構(gòu)造函數(shù)的規(guī)則:
1. 通常情況下,會(huì)選擇默認(rèn)無參構(gòu)造函數(shù)或者自己添加的無參構(gòu)造函數(shù)。
2. 如果有帶參構(gòu)造函數(shù),且被@Parameters注解,就會(huì)選擇該帶參構(gòu)造函數(shù)。
3. 如果同時(shí)有無參構(gòu)造函數(shù)和帶參構(gòu)造函數(shù),且?guī)?gòu)造函數(shù)沒有被@Parameters注解,選擇無參構(gòu)造函數(shù)。
4. 如果只有帶參構(gòu)造函數(shù),但是帶參構(gòu)造函數(shù)沒有被@Parameters注解,執(zhí)行測試函數(shù)時(shí)拋出org.testng.TestNGException。
對于帶參構(gòu)造函數(shù)的測試類,使用@Factory注解,不僅可以解決帶參構(gòu)造函數(shù)沒有被@Parameters注解而導(dǎo)致的org.testng.TestNGException,而且還可以充分發(fā)揮TestNG參數(shù)化測試的優(yōu)勢。以添加如下@Factory注解的代碼為例:
@Factory public static Object[] create() { System.out.println("Create test objects!"); List<WebTest> objectList = new ArrayList<WebTest>(); for(int i=1; i<4; i++) { objectList.add(new WebTest(i*10)); } return objectList.toArray(); } |
上面代碼會(huì)創(chuàng)建3個(gè)stayTime分別為10,20,30的測試實(shí)例。如果使用@Parameters注解,必須創(chuàng)建3個(gè)test分別將10,20,30從testng.xml傳入。因此,@Factory為帶參構(gòu)造函數(shù)的類創(chuàng)建一系列有規(guī)律的測試實(shí)例提供了便利。
posted on 2014-08-06 10:16 順其自然EVO 閱讀(300) 評(píng)論(0) 編輯 收藏