JUnit中有许多处理异常的方法 (JUnit中有3种处理异常的方法。选择哪一种呢? JUnit ExpectedException规则:超越了基础 )。 在本文中,我将介绍建议尝试的catch-exception库。 简而言之, catch-exceptions是一个库,可在一行代码中捕获异常,并使它们可用于进一步分析。

通过Maven安装

为了快速入门,我使用了带有一组测试依赖项( JUnit,Mocito,Hamcrest,AssertJ )的单元测试演示项目,并添加了catch-exceptions

<dependency><groupId>com.googlecode.catch-exception</groupId><artifactId>catch-exception</artifactId><version>1.2.0</version><scope>test</scope>
</dependency>

因此,依赖关系树如下所示:

[INFO] --- maven-dependency-plugin:2.1:tree @ unit-testing-demo ---
[INFO] com.github.kolorobot:unit-testing-demo:jar:1.0.0-SNAPSHOT
[INFO] +- org.slf4j:slf4j-api:jar:1.5.10:compile
[INFO] +- org.slf4j:jcl-over-slf4j:jar:1.5.10:runtime
[INFO] +- org.slf4j:slf4j-log4j12:jar:1.5.10:runtime
[INFO] +- log4j:log4j:jar:1.2.15:runtime
[INFO] +- junit:junit:jar:4.11:test
[INFO] +- org.mockito:mockito-core:jar:1.9.5:test
[INFO] +- org.assertj:assertj-core:jar:1.5.0:test
[INFO] +- org.hamcrest:hamcrest-core:jar:1.3:test
[INFO] +- org.hamcrest:hamcrest-library:jar:1.3:test
[INFO] +- org.objenesis:objenesis:jar:1.3:test
[INFO] \- com.googlecode.catch-exception:catch-exception:jar:1.2.0:test

入门

被测系统(SUT):

class ExceptionThrower {void someMethod() {throw new RuntimeException("Runtime exception occurred");}void someOtherMethod() {throw new RuntimeException("Runtime exception occurred",new IllegalStateException("Illegal state"));}void yetAnotherMethod(int code) {throw new CustomException(code);}
}

带有AssertJ断言的基本catch-exception BDD样式方法示例:

import org.junit.Test;import static com.googlecode.catchexception.CatchException.*;
import static com.googlecode.catchexception.apis.CatchExceptionAssertJ.*;public class CatchExceptionsTest {@Testpublic void verifiesTypeAndMessage() {when(new SomeClass()).someMethod();then(caughtException()).isInstanceOf(RuntimeException.class).hasMessage("Runtime exception occurred").hasMessageStartingWith("Runtime").hasMessageEndingWith("occured").hasMessageContaining("exception").hasNoCause();               }
}

看起来不错。 简洁,可读。 没有JUnit运行者。 请注意,我指定了我希望引发异常的SomeClass方法。 可以想象,我可以在一个测试中检查多个异常。 尽管我不推荐这种方法,因为这可能违反了测试的单一责任。

顺便说一句,如果您正在使用Eclipse,这可能对您来说很方便: 在Eclipse中创建JUnit测试时,改进具有静态成员类型的内容辅助

查明原因

我认为以下代码无需评论:

import org.junit.Test;import static com.googlecode.catchexception.CatchException.*;
import static com.googlecode.catchexception.apis.CatchExceptionAssertJ.*;public class CatchExceptionsTest {@Testpublic void verifiesCauseType() {when(new ExceptionThrower()).someOtherMethod();then(caughtException()).isInstanceOf(RuntimeException.class).hasMessage("Runtime exception occurred").hasCauseExactlyInstanceOf(IllegalStateException.class).hasRootCauseExactlyInstanceOf(IllegalStateException.class);}
}

验证Hamcrest的自定义例外

为了验证我用我以前的Hamcrest匹配代码自定义异常后 :

class CustomException extends RuntimeException {private final int code;public CustomException(int code) {this.code = code;}public int getCode() {return code;}
}class ExceptionCodeMatches extends TypeSafeMatcher<CustomException> {private int expectedCode;public ExceptionCodeMatches(int expectedCode) {this.expectedCode = expectedCode;}@Overrideprotected boolean matchesSafely(CustomException item) {return item.getCode() == expectedCode;}@Overridepublic void describeTo(Description description) {description.appendText("expects code ").appendValue(expectedCode);}@Overrideprotected void describeMismatchSafely(CustomException item, Description mismatchDescription) {mismatchDescription.appendText("was ").appendValue(item.getCode());}
}

和测试:

import org.junit.Test;import static com.googlecode.catchexception.CatchException.*;
import static org.junit.Assert.*;public class CatchExceptionsTest {@Testpublic void verifiesCustomException() {catchException(new ExceptionThrower(), CustomException.class).yetAnotherMethod(500);assertThat((CustomException) caughtException(), new ExceptionCodeMatcher(500));}
}

摘要

捕获异常看起来真的很好。 快速入门很容易。 我看到了一些优于JUnit方法规则的优点。 如果有机会,我将更彻底地调查图书馆,希望在一个实际项目中进行。

  • 可以在这里找到本文的源代码: 单元测试演示

如果您有兴趣,请查看我的其他帖子:

  • 在JUnit中处理异常的3种方法。 选择哪一个?
  • JUnit ExpectedException规则:超越基础
  • 如何:在Maven项目(JUnit,Mocito,Hamcrest,AssertJ)中测试依赖项
  • 在Eclipse中创建JUnit测试时,改进具有静态成员类型的内容辅助

翻译自: https://www.javacodegeeks.com/2014/04/yet-another-way-to-handle-exceptions-in-junit-catch-exception.html

处理JUnit中异常的另一种方法:catch-exception相关推荐

  1. junit:junit_处理JUnit中异常的另一种方法:catch-exception

    junit:junit JUnit中有许多处理异常的方法 (JUnit中有3种处理异常的方法.选择哪一种? JUnit ExpectedException规则:超越了基础 ). 在这篇文章中,我将介绍 ...

  2. java多线程同步的四种方法_java中实现多线程的两种方法

    java多线程有几种实现方法,都是什么?同步有几种实java中多线程的实现方法有两种:1.直接继承thread类:2.实现runnable接口:同步的实现方法有五种:1.同步方法:2.同步代码块:3. ...

  3. 多元高斯分布异常检测代码_数据科学 | 异常检测的N种方法,阿里工程师都盘出来了...

    ↑↑↑↑↑点击上方蓝色字关注我们! 『运筹OR帷幄』转载 作者:黎伟斌.胡熠.王皓 编者按: 异常检测在信用反欺诈,广告投放,工业质检等领域中有着广泛的应用,同时也是数据分析的重要方法之一.随着数据量 ...

  4. 在JavaScript中重复字符串的三种方法

    In this article, I'll explain how to solve freeCodeCamp's "Repeat a string repeat a string" ...

  5. 在js中加html_在HTML文档中嵌入JavaScript的四种方法

    在HTML里嵌入JavaScript 在HTML文档里嵌入客户端JavaScript代码有4中方法: 1.内嵌,放置在标签之间  (少): 2.放置在有 3.放置自HTML事件处理程序中,该事件处理程 ...

  6. html怎么样取jsp中的路径,jsp中获得路径的两种方法和获得url路径的方法(推荐)

    是解决相对路径的问题,可返回站点的根路径. //这样获得的是绝对路径 //这样获得的是相对路径 能够更有效的防治连接的失效. request.getContextPath()得到的是项目的名字,如果项 ...

  7. mysql 统计条目_mysql 统计表中条目数量的几种方法

    mysql 统计表中条目数量的几种方法 展开 通常的方法是: select count(*) from `table_name` select count(1) from `table_name` s ...

  8. python写错了怎么更改-Python中修改字符串的四种方法

    在Python中,字符串是不可变类型,即无法直接修改字符串的某一位字符. 因此改变一个字符串的元素需要新建一个新的字符串. 常见的修改方法有以下4种. 方法1:将字符串转换成列表后修改值,然后用joi ...

  9. python自带的shell是什么-python中执行shell的两种方法总结

    一.使用python内置commands模块执行shell commands对Python的os.popen()进行了封装,使用SHELL命令字符串作为其参数,返回命令的结果数据以及命令执行的状态: ...

最新文章

  1. 数据为王的时代,如何用图谱挖掘商业数据背后的宝藏?
  2. (每日一题)P3723 [AH2017/HNOI2017]礼物(经典FFT)
  3. 答案计算机应用技术试卷,计算机应用与技术试卷A及答案
  4. python是一种动态语言、这意味着_【python编程的优点是什么?难怪选择python的人越来越多了】- 环球网校...
  5. phoneGap2.9+eclipse开发环境和helloword案例
  6. 《TCP/IP详解》学习笔记(七):广播和多播、IGMP协议
  7. 判断是否有小数_一线老师笔记:数学判断题拿高分的技巧
  8. Pandas 文本数据方法 get_dummies()
  9. 51Nod 1289 大鱼吃小鱼 栈的简单模拟
  10. 系统辨识理论及应用_企业战略分析的理论工具
  11. 达观数据助力浙江大华构建企业级知识搜索共享平台,盘活沉淀数据
  12. android 歌词同步 换行,AS3歌词同步详解
  13. thinkphp 的 whereIN() 、where IN 如何使用?
  14. ios html自动进入app,iOS 通过浏览器打开app
  15. golang mysql 非阻塞_Golang 实现轻量、快速的基于 Reactor 模式的非阻塞 TCP 网络库...
  16. Nim 游戏和 SG 函数
  17. 经过前面几天的学习已经初步了解到了Java 今天开始学习Java的 对象与类
  18. 壹 2.2 整数表示
  19. 在ESG领域,区块链究竟怎么用?
  20. 往事如烟 - 笑傲江湖

热门文章

  1. anroid 内存溢出 Bitmap OutOfMemoryError
  2. 攻城掠地端mysql_【图片】攻城掠地单机版本服务端+攻城掠地GM工具【单兆权吧】_百度贴吧...
  3. 云服务器mqtt协议,云服务器mqtt协议
  4. 算法运行时间中的对数
  5. jwt令牌_JWT令牌的秘密轮换
  6. 对话框 函数_通过函数式编程实现动态对话框处理程序
  7. jgroups_JGroups:无需额外基础架构的领导人选举
  8. java转换为c#_将25k行C#转换为Java的经验教训
  9. guice 实例_使用Google Guice消除实例之间的歧义
  10. 使用SoapUI调用安全WCF SOAP服务–第1部分,该服务