使用JUnit来测试Java代码中的异常有很多种方式,你知道几种?

给定这样一个class。

Person.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class Person {

    private String name;
private int age; public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public int getAge() {
return age;
} public void setAge(int age) { if (age < 0 ) {
throw new IllegalArgumentException("age is invalid");
}
this.age = age;
}
}

我们来测试setAge方法。

Try-catch 方式

1
2
3
4
5
6
7
8
9
10
11
    @Test
public void shouldGetExceptionWhenAgeLessThan0() {
Person person = new Person();
try {
person.setAge(-1);
fail("should get IllegalArgumentException");
} catch (IllegalArgumentException ex) {
assertThat(ex.getMessage(),containsString("age is invalid"));
} }

这是最容易想到的一种方式,但是太啰嗦。

JUnit annotation方式

JUnit中提供了一个expected的annotation来检查异常。

1
2
3
4
5
6
    @Test(expected = IllegalArgumentException.class)
public void shouldGetExceptionWhenAgeLessThan0() {
Person person = new Person();
person.setAge(-1); }

这种方式看起来要简洁多了,但是无法检查异常中的消息。

ExpectedException rule

JUnit7以后提供了一个叫做ExpectedException的Rule来实现对异常的测试。

1
2
3
4
5
6
7
8
9
10
11
12
    @Rule
public ExpectedException exception = ExpectedException.none(); @Test
public void shouldGetExceptionWhenAgeLessThan0() { Person person = new Person();
exception.expect(IllegalArgumentException.class);
exception.expectMessage(containsString("age is invalid"));
person.setAge(-1); }

这种方式既可以检查异常类型,也可以验证异常中的消息。

使用catch-exception库

有个catch-exception库也可以实现对异常的测试。

首先引用该库。

pom.xml
1
2
3
4
5
6
        <dependency>
<groupId>com.googlecode.catch-exception</groupId>
<artifactId>catch-exception</artifactId>
<version>1.2.0</version>
<scope>test</scope> <!-- test scope to use it only in tests -->
</dependency>

然后这样书写测试。

1
2
3
4
5
6
7
8
    @Test
public void shouldGetExceptionWhenAgeLessThan0() {
Person person = new Person();
catchException(person).setAge(-1);
assertThat(caughtException(),instanceOf(IllegalArgumentException.class));
assertThat(caughtException().getMessage(), containsString("age is invalid")); }

这样的好处是可以精准的验证异常是被测方法抛出来的,而不是其它方法抛出来的。

catch-exception库还提供了多种API来进行测试。

先加载fest-assertion库。

1
2
3
4
5
        <dependency>
<groupId>org.easytesting</groupId>
<artifactId>fest-assert-core</artifactId>
<version>2.0M10</version>
</dependency>

然后可以书写BDD风格的测试。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
    @Test
public void shouldGetExceptionWhenAgeLessThan0() {
// given
Person person = new Person(); // when
when(person).setAge(-1); // then
then(caughtException())
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("age is invalid")
.hasNoCause();
}

如果喜欢Hamcrest风格的验证风格的话,catch-exception也提供了相应的Matcher API。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
    @Test
public void shouldGetExceptionWhenAgeLessThan0() {
// given
Person person = new Person(); // when
when(person).setAge(-1); // then
assertThat(caughtException(), allOf(
instanceOf(IllegalArgumentException.class)
, hasMessage("age is invalid")
,hasNoCause()));
}

第一种最土鳖,第二种最简洁,第四种最靠谱。

Java中测试异常的多种方式的更多相关文章

  1. 夯实Java基础系列10:深入理解Java中的异常体系

    目录 为什么要使用异常 异常基本定义 异常体系 初识异常 异常和错误 异常的处理方式 "不负责任"的throws 纠结的finally throw : JRE也使用的关键字 异常调 ...

  2. 【Java心得总结二】浅谈Java中的异常

    作为一个面向对象编程的程序员对于 下面的一句一定非常熟悉: try { // 代码块 } catch(Exception e) { // 异常处理 } finally { // 清理工作 } 就是面向 ...

  3. Java中的异常-Throwable-Error-Exception-RuntimeExcetpion-throw-throws-try catch

    今天在做一个将String转换为Integer的功能时,发现Integer.parseInte()会抛出异常NumberFormatException. 函数Integer.parseInt(Stri ...

  4. java 获取classpath下文件多种方式

    java 获取classpath下文件多种方式 一:properties下配置 在resources下定义server.properties register.jks.path=classpath\: ...

  5. Java中反射的三种常用方式

    Java中反射的三种常用方式 package com.xiaohao.test; public class Test{ public static void main(String[] args) t ...

  6. Java中的异常详解

    一.异常定义 阻止当前方法或作用域继续执行的问题,称为异常 二.异常分析      所有不正常类都继承Throwable类,这个类主要有两个子类Error类和Exception类.Error指系统错误 ...

  7. Java中的异常和处理详解

    简介 程序运行时,发生的不被期望的事件,它阻止了程序按照程序员的预期正常执行,这就是异常.异常发生时,是任程序自生自灭,立刻退出终止,还是输出错误给用户?或者用C语言风格:用函数返回值作为执行状态?. ...

  8. Java中的异常简介

    Java中异常的分类 Java中的异常机制是针对正常运行程序的一个必要补充,一般来说没有加入异常机制,程序也能正常运营,但是,由于入参.程序逻辑的严谨度,总会有期望之外的结果生成,因此加入异常机制的补 ...

  9. Java中创建对象的五种方式

    我们总是讨论没有对象就去new一个对象,创建对象的方式在我这里变成了根深蒂固的new方式创建,但是其实创建对象的方式还是有很多种的,不单单有new方式创建对象,还有使用反射机制创建对象,使用clone ...

随机推荐

  1. python核心编程笔记

    1.python的对象是通过引用传递的. 2.多元赋值: x, y = y, x

  2. 用JDBC做账号注册登陆

    一.先用JDBC做账号登陆 方法一:用createStatement方法做账号登陆 测试结果:当输入正确账号密码时:当输入错误账号密码时: 当用注入攻击输入账号密码时: 注入攻击的原理是 输入任意值' ...

  3. 51nod 1138 连续整数的和(数学公式)

    1138 连续整数的和 #include <iostream> #include <cmath> #include <cstdio> using namespace ...

  4. SVN强制解锁操作

    如果是其他人锁定文件,而你期望对此文件操作,可进行偷锁操作: 1,将被锁定文件SVN Check out-到本机硬盘. 2,点击文件右键,选择get lock 3,勾上steal the locks ...

  5. vbox 虚拟机共享文件夹 debian

    主机64位windows7 虚拟机Debian 8 64位 注意:在网络更新时,可能需要修改 etc/apt/sources.list 文件,把前几条从CD更新删除掉,这样就会从网络更新 1.vbox ...

  6. 【转】测试LibreOffice SDK 开发环境配置(Windows)

    原文:http://www.aqcoder.com/blog/detail/id/7441186b-93fd-482c-b4d7-0facd1ee498d 下载与安装 LibreOffice 主页:h ...

  7. Redis第一篇(Redis单机版本安装及启动)

    安装: 1 2 3 4 5 [root@M2_Redis1 ~]# yum install gcc gcc-c++     (安装依赖) [root@M2_Redis1 tools]# wget ht ...

  8. Windows server 修改mysql端口

    [此方法对mysql免安装版本适用] (最好先停止mysql服务) 1.解压MySQL后,在MySQL根目录下有一个my-default.ini,将该文件复制粘贴一份,重命名为:my.ini,还是放在 ...

  9. iOS-延时操作汇总

    在iOS开发中,一个操作我们希望不要立刻执行,而是等上几秒之后再来处理,这时我们就需要延时处理,我们来看看这些方 1.最直接的方法performSelector:withObject:afterDel ...

  10. Linux Ubuntu12.04下安装OpenCv2.4.10

    参考 http://blog.sina.com.cn/s/blog_53b0956801010lfu.html 捣鼓了一个晚上了,OpenCv还没装好,本来以为看个类似的比如Ubuntu安装OpenC ...