Junit 测试中如何对异常进行断言

本文对在 Junit 测试中如何对异常进行断言的几种方法进行说明。

使用 Junit 5

如果你使用 Junit 5 的话,你可以直接使用 assertThrows 方法来对异常进行断言。

代码如下:

        Exception exception = assertThrows(NumberFormatException.class, () -> {
            new Integer("one");
        });
        System.out.println(exception);

使用 AssertJ

使用 AssertJ ,你可以有不少方法进行选择。

我们尝试使用 assertThatThrownBy 和 assertThatExceptionOfType 2 个方法。

这 2 个方法的写法有点不一样,但是整体效果是差不多的。

考察如下代码:

//        AssertJ assertThatThrownBy
        assertThatThrownBy(() -> {
            new Integer("one");
        }).isInstanceOf(NumberFormatException.class).hasMessageStartingWith("For input string");

        // AssertJ assertThatExceptionOfType
        assertThatExceptionOfType(NumberFormatException.class).isThrownBy(() -> {
            new Integer("one");
        });

上面代码中,对有关断言的使用进行了一些说明。

Junit 测试中如何对异常进行断言 - 测试发布 - OSSEZhttps://www.ossez.com/t/junit/13989

相关推荐
以卿a15 分钟前
C++ 模板初阶
开发语言·c++
s:10319 分钟前
【框架】参考 Spring Security 安全框架设计出,轻量化高可扩展的身份认证与授权架构
java·开发语言
道不尽世间的沧桑1 小时前
第17篇:网络请求与Axios集成
开发语言·前端·javascript
久绊A1 小时前
Python 基本语法的详细解释
开发语言·windows·python
南山十一少3 小时前
Spring Security+JWT+Redis实现项目级前后端分离认证授权
java·spring·bootstrap
软件黑马王子5 小时前
C#初级教程(4)——流程控制:从基础到实践
开发语言·c#
闲猫5 小时前
go orm GORM
开发语言·后端·golang
427724005 小时前
IDEA使用git不提示账号密码登录,而是输入token问题解决
java·git·intellij-idea
chengooooooo5 小时前
苍穹外卖day8 地址上传 用户下单 订单支付
java·服务器·数据库
李长渊哦5 小时前
常用的 JVM 参数:配置与优化指南
java·jvm