要運行測試,請用 javac 編譯類,然后用以下命令調用 TestNG :
java -ea -classpath .;testng.jar;commons-lang-2.0.jar com.beust.testng.TestNG testng.xml
在這里,選項 -ea 告訴 JVM 處理斷言(在斷言失敗時拋出異常);運行這個例子只需要 testng.jar 和 commons-lang-2.0.jar 這兩個庫,而 com.beust.testng.TestNG 是 TestNG 的主類。對于所有那些已經非常高興地忘記了 java 和 javac 的神秘語法的開發人員來說,還提供了一個有用的 Ant 任務。作為例子,清單 3 演示了本文發布的示例應用程序的 Ant 構建文件。請注意與類 com.beust.testng.TestNGAntTask 關聯的 testng 任務的定義,以及它在 test 目標中相當簡單的用法。
清單 3. 帶有 TestNG 任務的 Ant 構建文件
<project name="sample" default="test" basedir=".">
<!-- COMPILE TESTS-->
<path id="cpath">
<pathelement location="testng.jar"/>
<pathelement location="commons-lang-2.0.jar"/>
</path>
<target name="compile">
<echo message="compiling tests"/>
<mkdir dir="classes"/>
<javac debug="true"
source="1.5" classpathref="cpath"
srcdir="src" destdir="classes"/>
</target>
<!-- RUN TESTS-->
<taskdef name="testng"
classname="com.beust.testng.TestNGAntTask"
classpathref="cpath"/>
<path id="runpath">
<path refid="cpath"/>
<pathelement location="classes"/>
</path>
<target name="test" depends="compile">
<echo message="running tests"/>
<testng fork="yes" classpathref="runpath" outputDir="test-output">
<fileset dir="src" includes="testng.xml"/>
<jvmarg value="-ea" />
</testng>
</target>
</project>
如果一切正常,那么應當在控制臺中看到測試結果。而且,TestNG 還在當前目錄下自動創建了一個叫做 test-output 的文件夾,并在其中創建了一份非常好的 HTML 報告。
定義測試組
TestNG 另外一個有趣的特性是其定義測試組的能力。每個測試方法都可以與一個或多個組相關聯,但可以選擇只運行某個測試組。要把測試加入測試組,只要把組指定為 @Test 標注的參數,使用的語法如下:
@Test(groups = {"tests.string"})
在這個具體的例子中,您聲明:標注的方法屬于 tests.string 組。因為參數 groups 是一個數組,所以可以指定多個組,組名之間用逗號分隔。例如,在示例應用程序中,您可以為 String、Number 以及 boolean 創建不同的測試,然后如清單 4 所示配置 TestNG, 有選擇地運行它們.
清單 4. 帶有不同組的配置文件
<!DOCTYPE suite SYSTEM "http://beust.com/testng/testng-1.0.dtd" >
<suite name="My suite">
<test name="Simple example">
<groups>
<run>
<include name="tests.string" />
<include name="tests.math" />
<exclude name="tests.boolean"/>
</run>
</groups>
<classes>
.... list classes here....
</classes>
</test>
</suite>
顯然,當運行不同的測試組時,HTML 報告能夠在單一列表中顯示所有測試,也可以在獨立的列表中顯示每個組的測試,從而能夠立即理解問題的來源。
配置方法
使用 TestNG,不僅可以指定測試方法,還可以用專門的標注 @Configuration 指定類中的其他特定方法,這些方法叫做 配置方法。配置方法有四種類型:
beforeTestClass 方法在類實例化之后,但是在測試方法運行之前執行。
afterTestClass 方法在類中的所有測試方法執行之后執行。
beforeTestMethod 方法在類中的任何測試方法執行之前執行。
afterTestMethod 方法在類中的每個測試方法執行之后執行。
測試類的生命周期
清單 5 演示了配置方法的一些示例。請注意,如果您使用組,那么配置方法也必須屬于某個組。而且,配置方法的四種類型彼此之間不是互斥的,所以可以把方法定義成同時屬于一種或多種配置方法類型。(作為例子,請參閱清單 5 中的 aroundTestMethods() 方法)。
清單 5. 配置方法示例
@Configuration(beforeTestClass = true, groups = {"tests.workflow"})
public void setUp()
{
System.out.println("Initializing...");
}
@Configuration(afterTestMethod = true, beforeTestMethod = true, groups = {"tests.workflow"})
public void aroundTestMethods()
{
System.out.println("Around Test");
}
TestNG 中的配置方法是 JUnit 的 setUp() 和 tearDown() 方法的增強版;它們的主要目的是為測試創建正確的執行上下文,并在測試用例執行之后刷新數據。