JUnit 判断 是否有异常抛出 异常类型是否正确 以及 异常的message 是否正确

参考:

http://stackoverflow.com/questions/2469911/how-do-i-assert-my-exception-message-with-junit-test-annotation

http://junit-team.github.io/junit/javadoc/4.10/org/junit/rules/ExpectedException.html

http://stackoverflow.com/questions/4489801/junit-test-analysing-expected-exceptions

http://jakegoulding.com/blog/2012/09/26/be-careful-when-using-junit-expected-exceptions/


方法一:使用ExpectedException

发生以下情况时,会认为失败

  1. 没有抛出异常
  2. 抛出的异常类型不正确
  3. 抛出的异常的message不正确

package com.yasi.test;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

public class UnitTest {
	
	@Rule
    public ExpectedException thrown= ExpectedException.none();
	
	@Test
	public void test1() {
		thrown.expect(NumberFormatException.class);
		thrown.expectMessage("The first error");
		
		throw new NumberFormatException("The first error");
	}
	
	@Test
	public void test2() {
		thrown.expect(IndexOutOfBoundsException.class);
		thrown.expectMessage("The second error");
		
		throw new IndexOutOfBoundsException("The second error");
	}
}


注意:

这里使用的expect() 函数原型是

public void expectMessage(String substring)
即, 传入的字符串不是要求 “刚好匹配”,而是, 只要 “被包含” 就算成功


这里有个问题,thrown.expectMessage("The first error") 一行,如果期望的message内容写成 "a",总是成功,但写成 "aa" 就失败。还不知道是怎么回事……


方法二:使用junit.Assert.fail

发生以下情况时,会认为失败

  1. 没有抛出异常
  2. 抛出的异常类型不正确

这里也可以用assertEquals来判断抛出的异常的message是否正确

package com.yasi.test;

import org.junit.Test;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

public class UnitTest {
	
	@Test
	public void test3() {
		try {
			long data = Long.parseLong("???");
			fail("NumberFormatException is not thrown as expected");
		} catch (Exception e) {
			assertTrue(e instanceof NumberFormatException);
		}
	}
	
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值