使用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. Sql Server 常用操作

    --DDL触发器CREATE   TRIGGER [TR_create_drop_alter_Table] ON DATABASE FOR CREATE_TABLE,DROP_table,ALTER_ ...

  2. 关于Java深clone 的例子学习

    之前http://www.cnblogs.com/lhppom/p/4857702.html里有提到关于Java的深克隆的学习,深浅区别就是在于仅复制对象引用和复制对象引用所指向的对象,最近在看< ...

  3. PHP那些非常有用却鲜有人知的函数

    PHP里有非常丰富的内置函数,很多我们都用过,但仍有很多的函数我们大部分人都不熟悉,可它们却十分的有用.这篇文章里,我列举了一些鲜为人知但会让你眼睛一亮的PHP函数. levenshtein() 你有 ...

  4. 【洛谷P3197】越狱

    本来还想了一会dp-- 然而一看数据范围明显是数论-- 那么推一推.. 我们发现可以用总方案数减去不会越狱的方案数 那么我们考虑在长度为n的数列中填数 首先第一个位置有m种选择,后面的位置: 总方案: ...

  5. mysql mHA manager 状态修改

    启动:nohup masterha_manager --conf=/etc/masterha/app1.cnf --remove_dead_master_conf --ignore_last_fail ...

  6. 汇总常用的jQuery操作Table tr td方法

    虽然现在DIV+CSS进行页的布局大行其道,但是很多地方使用table还是有很多优势,用table展示数据是比较方便的,下面汇总了jQuery操作Table tr td常用的方法,熟记这些操作技巧,下 ...

  7. RichTextBox着色与着色不闪

    近来写的一个数据查询分析器意外的快捷,不到两晚工夫就搞定了.完成度相当的高.当然少不了关键字着色,不过着色的代码来自的网上,看了一下感觉过多的循环 //文本框改变事件 int index = this ...

  8. Android中的IntentService

    首先说下,其他概念:Android中的本地服务与远程服务是什么? 本地服务:LocalService 应用程序内部------startService远程服务:RemoteService androi ...

  9. 界面显示两个ListView

    1.List界面布局 <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:an ...

  10. hdu 5661 Claris and XOR

    Claris and XOR Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)To ...