TestNG(Test Next Generation),顧名思義,下一代的測試框架。它是基于J2SE5.0的注釋特性的而構建的輕量級的單元測試框架結構。說起單元測試框架,大家都會自然地聯想到JUnit。用過JUnit3.X的程序開發人員,都會發現JUnit在提供了強大功能的同時,也存在很多令人沮喪的地方。其中一個問題就是,JUnit3.x 在每個測試方法調用前和調用后都會調用setUp()和tearDown()的方法。假如開發人員希望在不同的測試方法中重用同一個JDBC連接或者JNDI的Context的時候,會覺得很不方便。一般的解決這個問題的方法是使用靜態方法,而這樣的話,就必須小心并發控制的問題(多個線程訪問共享的靜態對象)。除此之外,JUnit 3.X對于多線程測試也比較麻煩,需要其他模塊的支持。
在Eclipse中安裝testNG很簡單。和安裝其他的plugin的方法相似。首先啟動Eclipse3.1,在Help->Software Update->Find and Install, 在彈出的向導中,選擇"Search New Features to Install", 點擊"New Remote Site",如圖1所示。在URL中輸入 http://beust.com/eclipse,點擊"OK"。如圖2所示,點擊"Finish",Eclipse會幫助你完成下面的安裝。熟悉Eclipse的讀者對這個過程一定不會覺得生疏。
4) 在文件瀏覽的對話框中,選擇{eclipse 3.1 home Directory}/plugins/com.beust.testng.eclipse_XXX/eclipse_testng.jar,以及 {eclipse 3.1 home directory}/plugins/com.beust.testng.eclipse_XXX/lib/testng-jdk14.jar/以及testng-jdk15.jar. 點擊OK
package com.catherine.lab.testng.firstTest; import com.beust.testng.annotations.*; public class FirstTestSample { public FirstTestSample() { super(); } @Test public void testPass() { assert true : "This test should pass."; }
@Test public void testFail() { assert false : "This test will fail"; }
@Configuration(beforeTestClass = true) public void doBeforeTests() { System.out.println("invoke before test class!"); }
@Configuration(afterTestClass = true) public void doAfterTests() { System.out.println("invoke after test class!"); } }