`
sophia_230
  • 浏览: 118703 次
  • 性别: Icon_minigender_2
  • 来自: 上海
社区版块
存档分类
最新评论

junit4

阅读更多

junit4比junit3.8有了较大的改进,主要体现在
1.增加了Annotation注解。
2.类不需要extends TestCase
3.方法名可以随便起
4.通过Annotation注解(@Test)来体现某个类为测试类
5.对异常处理方面有了较大改进,如:@Test(expected = Exception.class)通过expected参数大大简化了处理
6.新增了@BeforeClass,全局只执行一次。junit3.8里没有这样的方法。

   
package org.test;    
   
import junit.framework.Assert;    
   
import org.junit.Before;    
import org.junit.BeforeClass;    
import org.junit.Test;    
/** 
* 不需要再继承TestCase 
* 
*/   
public class AddTest2 {    
    public AddTest2(){    
         System.out.println("constructor invoked!");    
     }    
    private static Add add ;    
        
    /** 
      * junit4里新增的特性,必须是static的,全局只执行一次,在所以测试方法前执行,并且是在该测试类的构造函数执行前执行。仅执行一次 
      */   
    @BeforeClass   
    public static void globalInit(){    
         add = new Add();    
         System.out.println("global init");    
     }    
    /** 
      * 相当于junit3.8里的setUp(),每个测试方法执行前都会执行一次 
      */   
    @Before   
    public void init(){    
         System.out.println("init");    
     }    
    /** 
      * 相当于junit3.8里的tearDown 
      */   
    public void destroy(){    
         System.out.println("destroy");    
     }    
    /** 
      * junit4里方法名字可以随便起,但是必须满足 
      * 1)public 
      * 2) void 
      * 3) 方法没有参数 
      */   
    @Test   
    public void myAdd(){    
        int result = add.add(3, 5);    
         Assert.assertEquals(8, result);    
     }    
   
}   

 

执行结果:
global init
constructor invoked!
init

 

package org.test;    
   
import org.junit.Test;    
   
public class DivideTest2 {    
        
    private Divide divide ;    
    public void init(){    
         divide = new Divide();    
     }    
    /** 
      * 加了expected参数意思是,该方法必须抛出该异常,否则测试失败 
      * @throws Exception 
      */   
    @Test(expected = Exception.class)    
    public void myDivide() throws Exception{    
        int result = divide.divide(10, 0);    
     }    
   
}   

 

package org.test;    
   
import org.junit.runner.RunWith;    
import org.junit.runners.Suite;    
/** 
* RunWith注解的参数value值必须是一个测试运行器,也就是必须是org.junit.runner.Runner类或其子类。org.junit.runners.Suite是Runner的子类 
* 
*/   
@RunWith(Suite.class)    
@Suite.SuiteClasses({AddTest2.class,DivideTest2.class})    
public class TestAll1 {    
   
}   

package org.test;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;
/**
 * RunWith注解的参数value值必须是一个测试运行器,也就是必须是org.junit.runner.Runner类或其子类。org.junit.runners.Suite是Runner的子类
 *
 */
@RunWith(Suite.class)
@Suite.SuiteClasses({AddTest2.class,DivideTest2.class})
public class TestAll1 {

}
 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics