JUnit单元测试(2)

链接:

JUnit单元测试(1)


Before和After

在@Before中初始化测试资源
在@After中释放测试资源

Calculate calculate;
@Before
public void setUp() throws Exception {
    calculate = new Calculate();
}

@After
public void tearDown() throws Exception {
    calculate = null;
}
@Test
public void testPlus(){
	assertEquals(3,calculate.plus(1,2));
}

为什么要使用before和after?
用来保证test方法执行前会创建新的test实例,实例变量状态不会传递给下一个test方法。单个test方法执行前后会执行before和after方法。

同时还有@BeforeClass和@AfterClass静态方法,在所有测试开始前后执行。一般是做比较耗时的操作例如创建删除数据库等。对于上述四种方法的执行时间可以这样去理解。
在这里插入图片描述

异常测试

使用@Test(excepted = Exception.class)


参数化测试

如果待测数据的输入和输出是一组数据:
可以把测试数据组织起来,用不同的测试数据调用相同的方法。

demo:

@RunWith(Parameterized.class)
public class AbsTest{
	@Parameters
	public static Collection<?> data(){
		return Arrays.asList(new Object[][]{
			{0,1},{1,1},{-1,1}
		}
	}
	int input;
	int excepted;
	public AbsTest(int input, int excepted){
		this.input = input;
		this,excepted = excepted;
	}
}
@Test
public void testAbs(){
	int r = Math.abs(this.input);
	assertEquals(this.excepted,r);
}

注意:

  • 参数必须由静态方法data返回,返回类型为Collection<Object[]>,可用问号表示。
  • 静态方法必须标记@Parameters
  • 测试类必须标记@RunWith(Parameterized.class)
  • 构造方法参数必须与测试参数对应

超时测试

使用@Test(timeout = 1000) 设置超时,其中timeout的单位为ms。
注意的是,超时测试不能取代性能和压力测试。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值