对于使用验证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
“
);
}
@Test(expected =
IllegalStateException.
class
)
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();
@Test
public
void
testThrowExceptionWithRule()
{
expectedException.expect(IllegalStateException.class
);
throw
new
IllegalStateException(
“
test
“
);
}
@Test
public
void
testThrowExceptionAndMessageWithRule()
{
expectedException.expect(IllegalStateException.class
);
expectedException.expectMessage(“
fail
“
);
throw
new
IllegalStateException(
“expect fail
“
);
}
在stackoverflow中还有人提到了使用google-code中的catch-exception工程,今天没时间看了,回去好好研究一下。地址是:
http://code.google.com/p/catch-exception/
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/109016.html原文链接:https://javaforall.net
