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!"); } }