说来惭愧,虽然之前已经看过junit的源码了,也写了几篇博客,但是长时间不写test case,今天想要写抛exception相关的test case时,竟然不知道怎么写了。。。。。好记性不如烂笔头,记下来先~~
对于使用验证test case方法中抛出的异常,我起初想到的是一种比较简单的方法,但是显得比较繁琐:
@test
public void testoldstyle() {
try {
double value = math.random();
if(value < 0.5) {
throw new illegalstateexception("test");
}
assert.fail("expect illegalstateexception");
} catch(illegalstateexception e) {
}
}
google了一下,找到另外几种更加方便的方法:1,使用test注解中的expected字段判断抛出异常的类型。2,使用expectedexception的rule注解。
个人偏好用test注解中的expected字段,它先的更加简洁,不管读起来还是写起来都很方便,并且一目了然:
@test(expected = illegalstateexception.class)
public void testthrowexception() {
throw new illegalstateexception("test");
public void testnotthrowexception() {
system.out.println("no exception throws");
对rule注解的使用(只有在junit4.7以后才有这个功能),它提供了更加强大的功能,它可以同时检查异常类型以及异常消息内容,这些内容可以只包含其中的某些字符,expectedexception还支持使用hamcrest中的matcher,默认使用isinstanceof和stringcontains matcher。在blockjunit4classrunner的实现中,每一个test case运行时都会重新创建test class的实例,因而在使用expectedexception这个rule时,不用担心在多个test case之间相互影响的问题:
@rule
public final expectedexception expectedexception = expectedexception.none();
public void testthrowexceptionwithrule() {
expectedexception.expect(illegalstateexception.class);
public void testthrowexceptionandmessagewithrule() {
expectedexception.expectmessage("fail");
throw new illegalstateexception("expect fail");