最后,請單擊本文頂部或底部的Code圖標,下載 j-testng-sample.zip 文件,其中包含一些示例,演示了如何用 TestNG 為 Jakarta Commons Lang 編寫單元測試。在里面,可以找到這里給出的大多數代碼,還有其他一些示例。閱讀本文并不需要這些代碼,但是它可以幫助您更加深入地理解在這里介紹的概念。
TestNG 快速起步
TestNG 的測試類是普通的老式 Java 對象;您不需要擴展任何特殊的類,也不需要使用測試方法的任何命名約定:您只要用標注@Test通知框架這個類的方法是測試。清單 1 演示了實用類StringUtils的一個最簡單的測試。它測試StringUtils的兩個方法:isEmpty()方法檢測String是否為空;trim()方法從String兩端刪除控制字符。請注意,其中使用了 Java 指令assert來檢測錯誤情況。
package tests;
import com.beust.testng.annotations.*;
import org.apache.commons.lang.StringUtils;
public class StringUtilsTest
{
@Test
public void isEmpty()
{
assert StringUtils.isBlank(null);
assert StringUtils.isBlank("");
}
@Test
public void trim()
{
assert "foo".equals(StringUtils.trim(" foo "));
}
}
但是,在運行測試之前,必須用特殊的 XML 文件配置 TestNG,習慣上把這個文件命名為 testng.xml。這個文件的語法非常簡單,如清單 2 所示。這個文件首先定義測試套件My test suite,這個套件只包含一個測試First test,這個測試由StringUtilsTest類完成。
清單 2. TestNG 的配置文件 <!DOCTYPE suite SYSTEM "http://beust.com/testng/testng-1.0.dtd" ><suite name="My test suite">
<test name="First test">
<classes>
<class name="tests.StringUtilsTest" />
</classes>
</test>
</suite>
如果這個示例 testng.xml 文件看起來沒什么用處(只有一個測試類),那么好消息是:這實際上是您定義測試套件時惟一需要編寫的文件。還記得 JUnit 過去的日子么?在那些日子里,套件的定義可能分布在多個文件中:JUnit 的TestSuite文件,屬性文件,還有當然缺不了的 Ant 構建文件。使用 TestNG,所有必需的數據都集中在 testng.xml 文件中。不需要額外的TestSuite文件和構建文件。
要運行測試,請用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 報告。如果打開該報告并裝入 index.html,就可以看到與圖 1 中的頁面類似的頁面。
文章來源于領測軟件測試網 http://www.kjueaiud.com/