1. 程式人生 > >TestNG單元測試框架使用

TestNG單元測試框架使用

一、TestNG簡介和安裝

TestNG(Test Next Generation)是一個測試框架,和Unit類似,但引入了一些新的功能,使其功能更強大,使用更方便。TestNG作為Java專案的單元測試框架,在引數化測試、依賴測試和套件測試(分組概念)方面更加突出。 TestNG用於高階測試和複雜整合測試。 它的靈活性對於大型測試套件尤其有用。 此外,TestNG還涵蓋了整個核心的JUnit4功能。

可以在Eclipse中線上安裝,Help-Install new software像安裝其他外掛一樣,輸入其官方地址為http://beust.com/eclipse。或者下載之後離線安裝

,可以從此處下載,下載之後將features和plugins下的檔案,分別放到Eclipse中對應的資料夾下面即可。具體安裝的細節不多說了,網路上的文件很多。

安裝成功之後,可以看見在新建時多了TestNG class的選項。

testng class

二、一個簡單示例

建立如下兩個類:

//此類名為NewTest.java
package com.lupu;

import org.testng.annotations.Test;

public class NewTest {

    @Test
    public void test2() {
        System.out.print("NewTest-來自test2\n"
); } @Test public void test() { System.out.print("NewTest-來自test\n"); } @Test public void test3() { System.out.print("NewTest-來自test3\n"); } @Test(enabled = false) public void test4() { System.out.print("NewTest-來自test4\n"); } @Test
(timeOut=2000) public void test5() { System.out.print("NewTest-來自test5\n"); try { Thread.sleep(4000); } catch (InterruptedException e) { e.printStackTrace(); } } }

此類中,用@Test來定義測試方法,在@Test中支援非常多的配置,上面我們用跳過此方法和超時來做簡單的示例。

//此類名為NewTest2.java
package com.lupu;

import org.testng.annotations.AfterSuite;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.BeforeTest;

public class NewTest2 {

    @BeforeSuite
    public void beforeSuite() {
        System.out.print("[email protected]\n");
    }

    @AfterSuite
    public void afterSuite() {
        System.out.print("[email protected]\n");
    }

    @BeforeTest
    public void beforeTest() {
        System.out.print("[email protected]\n");

    }

    @AfterTest
    public void afterTest() {
        System.out.print("[email protected]\n");
    }
}

此類中用了註釋來執行測試類的配置,通過它們可以方便的進行一些配置操作。

接著,建立一個XML檔案來執行多個測試用例,同時也保證了結構清晰,testng.xml檔案內容如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >

<!-- @BeforeSuite -->
<suite name="TestAll">

    <!-- @BeforeTest -->
    <test name="case1">
        <classes>
            <class name="com.lupu.NewTest" />
            <class name="com.lupu.NewTest2" />

        </classes>
    </test>
    <!-- @AfterTest -->

    <!-- @BeforeTest -->
    <test name="case2">
        <classes>
            <class name="com.lupu.NewTest" />
        </classes>
    </test>
    <!-- @AfterTest -->

</suite>
<!-- @AfterSuite -->

設定用testng.xml執行,在testng.xml檔案中右鍵,選擇Suite,如下圖所示:

testNG.xml

設定完成之後,這時右鍵點選testng.xml可以看見,以TestNG Suite來執行:

run suite

執行之後,我們可以在控制檯下面檢視輸出和testng的執行結果:

testng result

Console控制檯的輸出如下所示:

[TestNG] Running:
  D:\Android\EclipseProjects\Java-testNG\testng.xml

[email protected]
[email protected]
NewTest-來自test
NewTest-來自test2
NewTest-來自test3
NewTest-來自test5
java.lang.InterruptedException: sleep interrupted
    at java.lang.Thread.sleep(Native Method)
    at com.lupu.NewTest.test5(NewTest.java:31)
    //此處省略大段的異常輸出資訊
    java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:745)
[email protected]
NewTest-來自test
NewTest-來自test2
NewTest-來自test3
NewTest-來自test5
java.lang.InterruptedException: sleep interrupted
    at java.lang.Thread.sleep(Native Method)
    at com.lupu.NewTest.test5(NewTest.java:31)
    //此處省略大段的異常輸出資訊java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:745)
[email protected]

===============================================
TestAll
Total tests run: 8, Failures: 2, Skips: 0
===============================================

此處的兩個Failures是我們在@Test中添加了超時時間,然後在方法中使它超時,則會執行失敗,這在一些效能測試中,可以確保方法在合理的時間內返回。

TestNG配置註解:

@BeforeSuite - 對於套件測試,在此套件中的所有測試執行之前執行。
@AfterSuite - 對於套件測試,在此套件中的所有測試執行之後執行。
//以上兩個註解,只會執行一次

@BeforeTest - 對於套件測試,在執行屬於<test>標籤內的類的任何測試方法之前執行。
@AfterTest - 對於套件測試,在執行屬於<test>標籤內的類的所有測試方法都已執行之後執行。


@BeforeGroups:在呼叫屬於該組的第一個測試方法之前執行。
@AfterGroups:在呼叫屬於組的最後一個測試方法之後執行。

@BeforeClass- 在當前類的第一個測試方法之前執行。
@AfterClass - 運行當前類中的所有測試方法之後都執行。

@BeforeMethod - 在每個測試方法之前執行。
@AfterMethod - 在每個測試方法之後執行。

三、更多常用功能

1、預期異常測試

使用TestNG expectedExceptions來測試程式碼中的預期異常丟擲,並且可以判斷Error Message是否匹配,如果匹配則此用例會通過。

@Test(expectedExceptions=IllegalArgumentException.class,expectedExceptionsMessageRegExp="Null")
    public void test5() {
        System.out.print("NewTest-來自test5\n");
        throw new IllegalArgumentException("Null");
    }

如上所示,我們在方法中丟擲一個異常,但是用expectedExceptions來判斷它,此時此方法可以通過。

2、分組測試

@Test(groups = {“group1”})
public void test2() {
System.out.print(“NewTest-來自test2\n”);
}

    //NewTest
    @Test(groups = {"group1"})
    public void test() {
        System.out.print("NewTest-來自test\n");
    }

    @Test(groups = {"group1","group2"})
    public void test3() {
        System.out.print("NewTest-來自test3\n");
    }

    //NewTest2
    @BeforeSuite(groups="group2")
    public void beforeSuite() {
        System.out.print("[email protected]\n");
    }

執行之後可以發現,輸出為:

NewTest2-@BeforeSuite
NewTest-來自test
NewTest-來自test2
NewTest-來自test3
NewTest-來自test3

上面用到的是分組測試,對一個方法我們可以指定多個分組名,這樣便可以有很多種組合了。也可以在工程目錄下建立多個xml檔案,去執行不同的方法。還可以對類進行分組測試,用法類似於對方法進行分組測試,不在贅述。

3、依賴測試

TestNG允許指定依賴關係:

在@Test註釋中使用屬性dependsOnMethods,或者在@Test註釋中使用屬性dependsOnGroups。如果被依賴的方法執行成功,則執行此方法;反之,則不執行。見下面程式碼片段:

    //Run if test5() is passed.
    @Test(dependsOnMethods="test5")
    public void test() {
        System.out.print("NewTest-來自test\n");
    }

    @Test
    public void test5() {
        System.out.print("NewTest-來自test5\n");
        throw new IllegalArgumentException("Null");
    }

這裡test5方法會執行失敗,而test方法依賴於test5方法,所以test方法不會執行。

4、引數化測試

引數化測試允許我們使用不同的值一次又一次地執行相同的測試。
TestNG可以通過兩種不同的方式將引數直接傳遞給測試方法:

  • 使用testng.xml,使程式碼和測試資料分離,方便維護
  • 使用資料提供者@DataProvider

1、使用testng.xml:

    @Test
    @Parameters("username")
    public void test2(String username) {
        System.out.print(username+"\n");
    }

在testng.xml中一定要定義叫做username的引數:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >

<suite name="TestAll">
    <parameter name="username" value="HelloWorld" />

    <test name="case1">
        <classes>
            <class name="com.lupu.NewTest" />
        </classes>
    </test>
</suite>

執行之後,就可以看見輸出的是我們定義的變量了。

2、使用DataProvider:

    @Test(dataProvider = "provideNumbers")
    public void testDp(int number, int expected) {
        Assert.assertEquals(number + 10, expected);
        System.out.println(number+ " "+expected);
    }

    @DataProvider(name = "provideNumbers")
    public Object[][] provideData() {
        return new Object[][] { { 10, 20 }, { 100, 110 }, { 200, 210 } };
    }

如上面程式碼片斷所示,用@DataProvider(name = XXX)來定義一個DataProvider,然後在需要使用的地方法前面使用@Test(dataProvider = “XXX”)即可呼叫,上面程式碼的輸出為:

10 20
100 110
200 210

@DataProvider支援傳遞一個物件引數;並且支援根據測試方法名稱傳遞不同的引數過去,用到的時候再檢視相關的文件即可。

5、測試報告

TestNG測試結果預設放在工程目錄下的test-output/資料夾下面,有xml和html兩種格式的報告。下圖展示的是html格式的報告,點選“Click to show all stack frames”,可以檢視相關的詳細資訊。但是它的報告並不美觀!

report