將JUint 4轉化爲TestNG

       對於大規模軟件的測試,TestNG在很多方面的確優於JUnit 4。在項目開發初期,可能選擇JUnit 4進行測試,但是到軟件開發到一定階段後,逐漸發現JUint 4不能滿足更高的要求。此時,使用TestNG可以更好地對軟件進行測試,那麼如何從之前的JUnit 4測試轉化爲TestNG呢?

        將JUnit 4測試轉化爲TestNG,首先要解決的是方法前面的annotation。雖然TestNG的annotation與JUint 4的annotation大部分在名稱和功能上都相同,但是有些還是不同。JUnit 4與TestNG的annotation對比如下圖:


上表中只是一些簡單annotation的對應關係,TestNG的最大的優勢在於其提供的參數化測試,包括從testng.xml文件和@DataProvider兩種方式提供參數。JUnit 4提供的參數化測試功能很有限,所以轉化爲TestNG測試之後,需要根據實際測試需要手動添加一些參數化測試代碼。

除了annotation之外,TestNG的斷言與JUnit 4在期望結果與實際結果的順序上也有些區別。好在TestNG的提供AssertJUnit與JUnit 4的順序是一致的,在轉換的時候,只需要import這個class就可以了。

Eclipse的TestNG plug-in提供了自動將JUnit 4的測試類自動轉換爲TestNG的功能。可以通過兩種途徑實現轉化:單個test class轉化和整個package或source folder轉化。

1. 單個test class轉化

單個test class轉化比較簡單。在test class中按Ctrl + 1快捷鍵,在彈出的菜單中選擇Convert to TestNG,整個test class就會自動轉化爲TestNG的test class。

實例如下:

JUnit 4的test class:

package com.ibm.testng.test;

import static org.junit.Assert.assertTrue;

import java.io.IOException;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.ibm.yuejming.Copyright;

/**
 * @author [email protected]
 */
@Copyright(Copyright.HEADER + "2013" + Copyright.FOOTER)
public class JUnitTest {
    @Before
    public void setUp() {}

    @Test(expected=IOException.class)
    public void test1() {
        assertTrue(true);
    }

    @Test
    public void test2() {}
    
    @After
    public void tearDown() {}
}

自動轉化後的TestNG的test class:
package com.ibm.testng.test;

import static org.testng.AssertJUnit.assertTrue;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeMethod;
import java.io.IOException;

import com.ibm.yuejming.Copyright;

/**
 * @author [email protected]
 */
@Copyright(Copyright.HEADER + "2013" + Copyright.FOOTER)
public class JUnitTest {
    @BeforeMethod
    public void setUp() {}

    @Test(expectedExceptions=IOException.class)
    public void test1() {
        assertTrue(true);
    }

    @Test
    public void test2() {}
    
    @AfterMethod
    public void tearDown() {}
}
轉化前後的對比:

1)annotation跟之前表格的對應關係實現自動轉化。

2)annotation對應import的class由JUnit 4的轉化爲TestNG的。

3)assert對應import的class由org.junit.Assert轉化爲org.testng.AssertJUnit。

2. 整個package或source folder轉化

        要實現整個package或source folder的自動轉化,選中需要轉化的package或者source folder,點擊右鍵,選中TestNG -> Convert to TestNG,就會出現Refactoring嚮導,後面根據需要進行選擇就可了。



發佈了34 篇原創文章 · 獲贊 22 · 訪問量 38萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章