junit4X系列--Exception
原文出处:http://www.blogjava.net/DLevin/archive/2012/11/02/390684.html。感谢作者的无私分享。
说来惭愧,虽然之前已经看过JUnit的源码了,也写了几篇博客,但是长时间不写Test Case,今天想要写抛Exception相关的test case时,竟然不知道怎么写了。。。。。好记性不如烂笔头,记下来先~~
对于使用验证Test Case方法中抛出的异常,我起初想到的是一种比较简单的方法,但是显得比较繁琐:
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字段,它先的更加简洁,不管读起来还是写起来都很方便,并且一目了然:
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之间相互影响的问题:
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/
最新文章
- JavaScript 中一些概念理解 :clientX、clientY、offsetX、offsetY、screenX、screenY
- 键盘事件触发的兼容tips
- How can I protect derived classes from breaking when I change the internal parts of the base class?
- AI(二):人脸识别
- 浏览器默认样式(user agent stylesheet)+cssreset
- iOS 证书及配置文件介绍
- 利用URLScan工具过滤URL中的特殊字符(仅针对IIS6)-- 解决IIS短文件名漏洞
- Android 使用httpClient POST 模拟发送 multipart表单内容
- 阿里druid 介绍及配置
- qt界面不显示的原因
- Unity3d C# Socket 下载文件 (同步到)
- 0517JS综合练习、挂事件练习
- Python内置函数(5)——bin
- ARM与FPGA通过spi通信设计2.spi master的实现
- Java 容器源码分析之 LinkedHashMap
- 【nodejs】初识 NodeJS(一)
- Linux安装配置JDK1.7
- python 全栈开发,Day54(jQuery的属性操作,使用jQuery操作input的value值,jQuery的文档操作)
- ThreadPoolExecutor最佳实践--如何选择线程数
- roadhog中如何拷贝文件