Posted on 2007-07-14 19:21 
云自无心水自闲 阅读(2715) 
评论(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却都不需要这样做。