[TestNG]TestNG和Junit4的參數(shù)化測試對比

TestNG系列:
TestNG和Junit4的參數(shù)化測試對比
TestNG運行指定測試套件
TestNG整合ReportNG
TestNG參數(shù)化測試實戰(zhàn)
TestNG+Spring/Spring Boot整合

參數(shù)化測試是測試數(shù)據(jù)和測試腳本分離的一種實現(xiàn)方式,我們可以根據(jù)測試目的設(shè)計不同的測試數(shù)據(jù)并將測試數(shù)據(jù)存儲在各種介質(zhì)(內(nèi)存规脸、硬盤)中聚凹,測試方法在執(zhí)行時獲取一組預(yù)設(shè)的測試數(shù)據(jù)執(zhí)行并給出結(jié)果

一、首先對比下TestNG和Junit的框架整合:

  • Spring+TestNG+Maven整合:

1.pom.xml中增加testng依賴:

        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>6.8.8</version>
            <scope>test</scope>
        </dependency>

2.測試類增加1條注解
@ContextConfiguration(locations = "classpath:applicationContext.xml")并繼承AbstractTestNGSpringContextTests褥傍,范例如下

@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class BaseTest extends AbstractTestNGSpringContextTests{
    @Test
    public void testMethods()
    {
        ......
    }
}
  • Spring+Junit+Maven整合:

1.pom.xml中增加junit依賴:

        <!--Junit版本-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.4</version>
            <scope>test</scope>
        </dependency>

2.測試類增加2條注解
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml"),如下:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class BaseTest{
    @Test
    public void testMethods()
    {
        ......
    }
}

二、再對比下二者參數(shù)化測試的實現(xiàn):

Junit4 參數(shù)化測試:

  • 步驟如下:
    1.通過@Parameters標(biāo)識靜態(tài)參數(shù)構(gòu)造方法
    2.通過測試類構(gòu)造方法引入?yún)?shù)
    3.測試方法使用參數(shù)
  • 源碼如下:
@RunWith(Parameterized.class)
public class AuthorizedMemberHSFTest extends AuthorizedServiceTest {

    private Long userId;
    private String userName;
    private String appName;
    private String channelId;
    private String secret;
    private String xcodeAppKey;
    private Long tenantId;
    private boolean expected;

    @Parameterized.Parameters
    public static Collection<Object[]> data() {
        return Arrays.asList(new Object[][]{
                {3253622341L, "arthur.hw", "ocs", "1703183528", "123456", "123", 905L, true},
                {3253622341L, "arthur.hw", "ocs", "1703183528", "123456", "123", 905L, true}});
    }

    public AuthorizedMemberHSFTest(Long userId,
                                   String userName,
                                   String appName,
                                   String channelId,
                                   String secret,
                                   String xcodeAppKey,
                                   Long tenantId,
                                   boolean expected) {
        this.userId = userId;
        this.userName = userName;
        this.appName = appName;
        this.channelId = channelId;
        this.secret = secret;
        this.xcodeAppKey = xcodeAppKey;
        this.tenantId = tenantId;
        this.expected = expected;
    }

    @Test
    public void authorizeMember() {
        // 01:prepare parameter
        Credentials credentials = new Credentials();

        credentials.setUserId(userId);
        credentials.setUserName(userName);
        credentials.setAppName(appName);
        credentials.setChannelId(channelId);  // channelId cant be null
        credentials.setSecret(secret);
        credentials.setXcodeAppKey(xcodeAppKey);
        credentials.setTenantId(tenantId);

        Result<AccessToken> result = new Result<AccessToken>();

        // 02 hsf execution
        try {
            result = authorizeService.authorizeMember(credentials);
        } catch (Exception ex) {
//            log.error(ex.getMessage());
        }

        // 03 assert
        Assert.assertEquals(result.isSuccess(), expected);
    }
} 

缺點:

  • 1個測試類只能有一個靜態(tài)的參數(shù)構(gòu)造方法data()
  • 測試類需要使用@RunWith(Parameterized.class),無法兼容spring-test的runner:@RunWith(SpringJUnit4ClassRunner.class)掘剪,會導(dǎo)致無法通過注解注入待測服務(wù)
  • 需要在測試類中添加一個構(gòu)造方法(一種冗余設(shè)計)

TestNG 參數(shù)化測試:

  • 步驟如下:
    1.通過@dataProvider注解標(biāo)識參數(shù)構(gòu)造方法
    2.測試方法在注解@Test中通過dataProvider屬性指定參數(shù)構(gòu)造方法腻格,便可在測試方法中使用參數(shù)
  • 源碼如下:
public class AuthorizedServiceTest extends BaseTest {
    @Resource
    protected AuthorizeService authorizeService;

    @BeforeClass
    public void init() throws Exception {
        ServiceUtil.waitServiceReady(authorizeService);
    }
}
public class AuthorizedMemberHSFTest extends AuthorizedServiceTest {
    @DataProvider
    public static Object[][] getParameters(Method method) {

        return new Object[][]{
                {3253622341L, "arthur.hw", "ocs", "1703183528", "123456", "123", 905L, true},
                {1L, "obama", "ocs", "323243242", "123", "123", 3L, true}};
    }

    @Test(dataProvider = "getParameters")
    public void authorizeMember(Long userId,
                                String userName,
                                String appName,
                                String channelId,
                                String secret,
                                String xcodeAppKey,
                                Long tenantId,
                                boolean expected) {

        // 01:prepare parameter
        Credentials credentials = new Credentials();

        credentials.setUserId(userId);
        credentials.setUserName(userName);
        credentials.setAppName(appName);
        credentials.setChannelId(channelId);  
        credentials.setSecret(secret);
        credentials.setXcodeAppKey(xcodeAppKey);
        credentials.setTenantId(tenantId);

        Result<AccessToken> result = new Result<AccessToken>();

        // 02 hsf execution
        try {
            result = authorizeService.authorizeMember(credentials);
        } catch (Exception ex) {
            log.error(ex.getMessage());
        }

        // 03 assert
        Assert.assertEquals(result.isSuccess(), expected);
    }
}

執(zhí)行結(jié)果:


d55b9f5814827446.png
d55b9f5814827446.png

除此之外画拾,TestNG還支持通過testng.xml構(gòu)造參數(shù):
1.這次我們使用maven來運行TestNG,可以參考http://maven.apache.org/surefire/maven-surefire-plugin/examples/testng.html
2.在src/test/java/resources下添加testng.xml文件菜职,其中通過<parameter/>構(gòu)造需要使用的參數(shù)和值

<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="testmain" verbose="1" >
    <parameter name="kilo" value="just for test"></parameter>
    <test name="authorizeService" >
        <classes>
            <class name="xxx.yyy.AuthorizedServiceTest" />
        </classes>
    </test>
</suite>

3.在pom.xml中添加maven-surfire-plugin插件配置:

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <configuration>
                    <suiteXmlFiles>
                        <suiteXmlFile>src/test/resources/testng.xml</suiteXmlFile>
                    </suiteXmlFiles>
                </configuration>
            </plugin>
        </plugins>
    </build>

4.測試方法添加參數(shù)引用:

    @Parameters({"kilo"})
    @Test
    public void authorizeServiceTestMethod(String kilo)
    {
        System.out.println(kilo);
    }

5.運行test:

mvn clean test
717de23629d36961.png
717de23629d36961.png

TestNG的參數(shù)化測試還有一些高級特性青抛,具體可以參考:http://testng.org/doc/documentation-main.html#parameters

可以看到,TestNG相比Junit酬核,基本Junit參數(shù)化測試的缺點都解決了:
1蜜另、一個測試類中可以有多個參數(shù)構(gòu)造方法,測試方法和參數(shù)構(gòu)造方法可以通過注解關(guān)聯(lián)起來
2嫡意、可以兼容spring的注解注入
3举瑰、無需添加構(gòu)造方法
同時代碼量較小

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市蔬螟,隨后出現(xiàn)的幾起案子此迅,更是在濱河造成了極大的恐慌,老刑警劉巖旧巾,帶你破解...
    沈念sama閱讀 218,858評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件邮屁,死亡現(xiàn)場離奇詭異,居然都是意外死亡菠齿,警方通過查閱死者的電腦和手機佑吝,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,372評論 3 395
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來绳匀,“玉大人芋忿,你說我怎么就攤上這事〖部茫” “怎么了戈钢?”我有些...
    開封第一講書人閱讀 165,282評論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長是尔。 經(jīng)常有香客問我殉了,道長,這世上最難降的妖魔是什么拟枚? 我笑而不...
    開封第一講書人閱讀 58,842評論 1 295
  • 正文 為了忘掉前任薪铜,我火速辦了婚禮众弓,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘隔箍。我一直安慰自己谓娃,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,857評論 6 392
  • 文/花漫 我一把揭開白布蜒滩。 她就那樣靜靜地躺著滨达,像睡著了一般。 火紅的嫁衣襯著肌膚如雪俯艰。 梳的紋絲不亂的頭發(fā)上捡遍,一...
    開封第一講書人閱讀 51,679評論 1 305
  • 那天,我揣著相機與錄音竹握,去河邊找鬼画株。 笑死,一個胖子當(dāng)著我的面吹牛涩搓,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播劈猪,決...
    沈念sama閱讀 40,406評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼昧甘,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了战得?” 一聲冷哼從身側(cè)響起充边,我...
    開封第一講書人閱讀 39,311評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎常侦,沒想到半個月后浇冰,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,767評論 1 315
  • 正文 獨居荒郊野嶺守林人離奇死亡聋亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,945評論 3 336
  • 正文 我和宋清朗相戀三年肘习,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片坡倔。...
    茶點故事閱讀 40,090評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡漂佩,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出罪塔,到底是詐尸還是另有隱情投蝉,我是刑警寧澤,帶...
    沈念sama閱讀 35,785評論 5 346
  • 正文 年R本政府宣布征堪,位于F島的核電站瘩缆,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏佃蚜。R本人自食惡果不足惜庸娱,卻給世界環(huán)境...
    茶點故事閱讀 41,420評論 3 331
  • 文/蒙蒙 一着绊、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧涌韩,春花似錦畔柔、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,988評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至雇毫,卻和暖如春玄捕,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背棚放。 一陣腳步聲響...
    開封第一講書人閱讀 33,101評論 1 271
  • 我被黑心中介騙來泰國打工枚粘, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人飘蚯。 一個月前我還...
    沈念sama閱讀 48,298評論 3 372
  • 正文 我出身青樓馍迄,卻偏偏與公主長得像,于是被迫代替她去往敵國和親局骤。 傳聞我的和親對象是個殘疾皇子攀圈,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,033評論 2 355

推薦閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn)峦甩,斷路器赘来,智...
    卡卡羅2017閱讀 134,659評論 18 139
  • Spring Boot 參考指南 介紹 轉(zhuǎn)載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 46,822評論 6 342
  • spring官方文檔:http://docs.spring.io/spring/docs/current/spri...
    牛馬風(fēng)情閱讀 1,684評論 0 3
  • 感謝原作者的奉獻,原作者博客地址:http://blog.csdn.net/zhu_ai_xin_520/arti...
    狼孩閱讀 14,057評論 1 35
  • 2014年是我高二那年凯傲,還是短發(fā)犬辰,教室在被全校師生調(diào)侃為青樓的那座教學(xué)樓。我記不起那年的冬天是怎樣冰单,春天又是怎樣幌缝,...
    仲童閱讀 224評論 0 1