只要做Java開發(fā)的,99%的都用過JUnit。在JUnit4里面除了@Test, @Before, @BeforeClass這樣基本的特性,JUnit4還有些很酷但是大家平時(shí)不太用的特性。我這里做一下介紹,大家可以用一下,或者至少把玩一下:) 以下特性都基于4.8版本。
ParallelComputer: 并行測試
當(dāng)需要同時(shí)測試testcase的時(shí)候,你不需要為自己寫thread來做這個(gè)事情。JUnit4已經(jīng)有了這個(gè)特性,而且還提供多種同步選擇。例如:
	    /**
	     * @author 盧聲遠(yuǎn)<michaellufhl@yahoo.com.cn>
	     */ 
	    public class ParallelComputerTest { 
	        
	       @Test 
	        public void test() {     
	          Class[] cls={ParallelTest1.class,ParallelTest2.class }; 
	           
	          //Parallel among classes 
	          JUnitCore.runClasses(ParallelComputer.classes(), cls); 
	           
	          //Parallel among methods in a class 
	          JUnitCore.runClasses(ParallelComputer.methods(), cls); 
	           
	          //Parallel all methods in all classes 
	          JUnitCore.runClasses(new ParallelComputer(true, true), cls);    
	        } 
	       public static class ParallelTest1{ 
	          @Test public void a(){} 
	          @Test public void b(){} 
	       } 
	       public static class ParallelTest2{ 
	          @Test public void a(){} 
	          @Test public void b(){} 
	       } 
	    } 
你有3種同步方式:
1: ParallelComputer.classes():所有測試類同時(shí)開始執(zhí)行,但是每個(gè)類里面的方法還是順序執(zhí)行。在例子里面ParallelTest1和ParallelTest2同時(shí)開始,但是各自的a(),b()還是順序執(zhí)行。
2: ParallelComputer.methods():測試類順序執(zhí)行,但是每個(gè)類里面的方法是同時(shí)開始執(zhí)行。在例子里面ParallelTest1的a()和b()同時(shí)開始,等結(jié)束之后再開始ParallelTest2。
3: new ParallelComputer(true, true):所有測試類里面方法同時(shí)開始執(zhí)行。在例子里面4個(gè)方法同時(shí)開始執(zhí)行。
很有意思吧。
Category: 分類測試
當(dāng)你有很多testcase,但是你不想每次都執(zhí)行一遍的時(shí)候。你可以把testcase分成若干類,然后可以分類有選擇的來執(zhí)行這些testcase。
例子:譬如你有2類testcase,一類是重要的用Important.class表示,還有一類不那么重要的用Secondary.class表示。
	    /**
	     * @author 盧聲遠(yuǎn)<michaellufhl@yahoo.com.cn>
	     */ 
	    interface Important{}; 
	    interface Secondary{}; 
	    @RunWith(Categories.class) 
	    @IncludeCategory(Important.class) 
	    @ExcludeCategory(Secondary.class) 
	    @SuiteClasses( { CategoryTest.Alpha.class,  
	                     CategoryTest.Beta.class }) 
	    public class CategoryTest { 
	        
	       @Category(Important.class) 
	       public static class Alpha{//Alpha is Important except b 
	          @Test  
	          public void a(){} 
	           
	          @Test 
	          @Category(Secondary.class) 
	          public void b(){} 
	       } 
	        
	       public static class Beta{ 
	          @Test  
	          @Category(Important.class) 
	          public void a(){}//a is Important 
	       } 
	    }