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

相关推荐
liangshanbo12152 小时前
JavaScript 面试题:Object.keys() 的返回顺序是无序的吗?
开发语言·javascript·ecmascript
朝朝辞暮i8 小时前
C++ 第 23 课:class —— 开始真正进入面向对象
开发语言·c++·算法
leikooo9 小时前
用餐厅和盘子理解栈和堆
java·数据结构·链表·rust
小师兄吃牛肉9 小时前
C语言篇:宏
c语言·开发语言
郑同学的笔记9 小时前
【c++随笔28】strcmp 和 memcmp对比
开发语言·c++
言乐69 小时前
Python根据无法识别搜索词找出可能输入内容模型
开发语言·python·django·virtualenv·pygame
weixin_3077791310 小时前
有限产能智能排产与动态重排智能体:从需求解构到技术实现
开发语言·人工智能·算法·架构
Ivanqhz10 小时前
激活函数在 Transformer 中的作用及各种变体简述
java·linux·数据库·人工智能·深度学习
kakakahahahaha10 小时前
Windows C盘临时文件清理:%temp%、Windows Temp、Prefetch、Windows.old与hiberfil.sys处理指南
c语言·开发语言·windows
朝朝辞暮i10 小时前
C++ 第 27 课:智能指针 shared_ptr
开发语言·c++·算法