`

junit4

阅读更多

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

Java代码 复制代码

 

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


Java代码 复制代码
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);
	}

}




Java代码 复制代码
  1. package org.test;   
  2.   
  3. import org.junit.runner.RunWith;   
  4. import org.junit.runners.Suite;   
  5. /**  
  6.  * RunWith注解的参数value值必须是一个测试运行器,也就是必须是org.junit.runner.Runner类或其子类。org.junit.runners.Suite是Runner的子类  
  7.  *  
  8.  */  
  9. @RunWith(Suite.class)   
  10. @Suite.SuiteClasses({AddTest2.class,DivideTest2.class})   
  11. public class TestAll1 {   
  12.   
  13. }  
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics