Junit4入门

1. Junit4全面引入了Annotation来执行我们编写的测试类

2.   Junit4并不要求测试类继承TestCase父类

3.   Junit4,在一个测试类中,所有被@Test注解所修饰的public void方法都是Test case,可以被Junit所执行。

4. Junit4中并不要求测试方法名以test开头,但是最好按照3.8的要求那样,以test作为测试方法名的开头

5. 在Junit4 通过@Before注解实现同setUp方法同样的功能,使用@After注解实现同tearDown方法同样的功能

6. Junit4中可以使用@BeforeClass与@AfterClass注解修饰一个publicstatic void no-arg的方法,这样被@BeforeClas注解所修饰的方法会在所有测试方法执行前执行; 被         @AfterClass注解所修饰的方法会在所有测试方法执行之后执行

7. @Ignore注解既可以用于修饰测试类和测试方法,当修饰测试类时,表示忽略掉类中的所有测试方法,当修饰测试方法时,表示忽略掉该测试方法

8. 参数化测试(Parameters): Parameterized类,@RunWith注解,@Parameters

   当一个测试类使用参数化运行器运行时,需要在类的声明处加上@RunWith(Parameterized)注解,表示该类将不使用Juint内建的运行器运行,而使用参数化运行器运行;在参数化运行类中提供参数的方法要使用@Parameters注解来修饰,同时在测试类的构造方法中为各个参数赋值(构造方法是Junit调用的),最后编写测试类,它根据参数的数组来运行测试多次。

例1:

被测试类:

package com.ebuair.junit4;

public class Calculator {
	public int add(int x, int y){
		try {
			Thread.sleep(500);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return x + y;
	}
	public int substract(int x,int y){
		return x - y;
	}
	public int multiply(int x,int y){
		return x * y;
	}
	public int devide(int x,int y) throws Exception{
		if(0 == y){
			throw new Exception("0不能为除数");
		}
		return x/y;
	}
}
测试类:

package com.ebuair.junti4;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

import com.ebuair.junit4.Calculator;


public class TestCalculator {
	
	private Calculator calculator;
	
	@BeforeClass
	public static void globalInit(){
		System.out.println("globalInit invoked!");
	}
	@AfterClass
	public static void globalDestory(){
		System.out.println("globalDestory invoked!");
	}
	
	//使用@Before实现与setUp方法同样的功能
	@Before
	public void setUp(){
		calculator = new Calculator();
		System.out.println("before");
	}
	
	//使用@After实现与setUp方法同样的功能
	@After
	public void tearDown(){
		System.out.println("after");
	}
	//  Optionally specify timeout in milliseconds to cause a test method to fail 
	//   if it takes longer than that number of milliseconds.
	@Test(timeout = 800) 
	public void testAdd(){
		int reslut = 0;
		reslut = calculator.add(3, 5);
		assertEquals(8, reslut);
	}
	//Optionally specify expected, a Throwable, to cause a test method to succeed
	//if an exception of the specified class is thrown by the method
	@Ignore
	@Test(expected = Exception.class)
	public void testDevide() throws Exception{
		int reult = 0;
		reult = calculator.devide(3, 0);
		assertEquals(0, reult);
	}
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值