Posted on 2007-07-14 19:21
云自無心水自閑 閱讀(2708)
評論(0) 編輯 收藏 所屬分類:
Java 、
心得體會
原文地址:http://www.ibm.com/developerworks/java/library/j-cq08296/?ca=dgr-lnxw07JUnit4vsTestNG
JUnit到了4.0以后,增加了許多新特性,變得更加靈活易用。但是另一個也是基于Annotations的TestNG在靈活易用方面已經走在了JUnit的前面。實際上,TestNG是基于Annotation的測試框架的先驅,那么這兩者之間的差別是什么呢,在這里,將對兩者進行一些簡單的比較。
首先兩者在外觀上看起來是非常相似的。使用起來都非常的簡便。但是從核心設計的出發點來說,兩者是不一樣的。JUnit一直將自己定位于單元測試框架,也就是說用于測試單個對象。而TestNG定位于更高層次的測試,因此具備了一些JUnit所沒有的功能。
A simple test case
At first glance, tests implemented in JUnit 4 and TestNG look remarkably similar. To see what I mean, take a look at the code in Listing 1, a JUnit 4 test that has a macro-fixture (a fixture that is called just once before any tests are run), which is denoted by the @BeforeClass
attribute:
先來看一個簡單的測試例子:
第一眼看上去,JUnit和TestNG幾乎一模一樣。
package test.com.acme.dona.dep;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.BeforeClass;
import org.junit.Test;


public class DependencyFinderTest
{
private static DependencyFinder finder;

@BeforeClass

public static void init() throws Exception
{
finder = new DependencyFinder();
}

@Test
public void verifyDependencies()

throws Exception
{
String targetClss =
"test.com.acme.dona.dep.DependencyFind";


Filter[] filtr = new Filter[]
{
new RegexPackageFilter("java|junit|org")};

Dependency[] deps =
finder.findDependencies(targetClss, filtr);

assertNotNull("deps was null", deps);
assertEquals("should be 5 large", 5, deps.length);
}
}
package test.com.acme.dona.dep;

import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Configuration;
import org.testng.annotations.Test;


public class DependencyFinderTest
{
private DependencyFinder finder;

@BeforeClass

private void init()
{
this.finder = new DependencyFinder();
}

@Test
public void verifyDependencies()

throws Exception
{
String targetClss =
"test.com.acme.dona.dep.DependencyFind";


Filter[] filtr = new Filter[]
{
new RegexPackageFilter("java|junit|org")};

Dependency[] deps =
finder.findDependencies(targetClss, filtr);
assertNotNull(deps, "deps was null" );
assertEquals(5, deps.length, "should be 5 large");
}
}
仔細觀察,會發現一些不一樣的地方。首先,JUnit要求BeforClass的方法為static,因此finder也隨之需要聲明為static。另外init方法必須聲明為public。而TestNG卻都不需要這樣做。