原文出处:http://www.blogjava.net/DLevin/archive/2012/11/02/390684.html。感谢作者的无私分享。

说来惭愧,虽然之前已经看过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");

    }

    

    @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/

最新文章

  1. JavaScript 中一些概念理解 :clientX、clientY、offsetX、offsetY、screenX、screenY
  2. 键盘事件触发的兼容tips
  3. How can I protect derived classes from breaking when I change the internal parts of the base class?
  4. AI(二):人脸识别
  5. 浏览器默认样式(user agent stylesheet)+cssreset
  6. iOS 证书及配置文件介绍
  7. 利用URLScan工具过滤URL中的特殊字符(仅针对IIS6)-- 解决IIS短文件名漏洞
  8. Android 使用httpClient POST 模拟发送 multipart表单内容
  9. 阿里druid 介绍及配置
  10. qt界面不显示的原因
  11. Unity3d C# Socket 下载文件 (同步到)
  12. 0517JS综合练习、挂事件练习
  13. Python内置函数(5)——bin
  14. ARM与FPGA通过spi通信设计2.spi master的实现
  15. Java 容器源码分析之 LinkedHashMap
  16. 【nodejs】初识 NodeJS(一)
  17. Linux安装配置JDK1.7
  18. python 全栈开发,Day54(jQuery的属性操作,使用jQuery操作input的value值,jQuery的文档操作)
  19. ThreadPoolExecutor最佳实践--如何选择线程数
  20. roadhog中如何拷贝文件

热门文章

  1. 用ildasm和ilasm对.net下的exe程序进行破解初探
  2. webapi框架搭建-日志管理log4net
  3. [转]在Mac系统中安装配置Tomcat及和Eclipse 配置
  4. (GO_GTD_1)基于OpenCV和QT,建立Android图像处理程序
  5. 如何使用 Q#
  6. 移动端300ms点击延迟
  7. 关于new Date()
  8. eslint 的基本配置介绍
  9. 使用socket实现的ftp文件传输服务器
  10. 异常笔记--java编程思想