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 测试中如何对异常进行断言 - 测试发布 - OSSEZicon-default.png?t=N7T8https://www.ossez.com/t/junit/13989

相关推荐

  1. Junit单元测试常用断言

    2024-05-10 01:42:02       26 阅读
  2. PHP如何进行异常处理?

    2024-05-10 01:42:02       63 阅读
  3. 高防服务器如何异常流量进行识别

    2024-05-10 01:42:02       43 阅读
  4. Junit常用断言

    2024-05-10 01:42:02       50 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-05-10 01:42:02       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-05-10 01:42:02       100 阅读
  3. 在Django里面运行非项目文件

    2024-05-10 01:42:02       82 阅读
  4. Python语言-面向对象

    2024-05-10 01:42:02       91 阅读

热门阅读

  1. 前端代码优化

    2024-05-10 01:42:02       35 阅读
  2. SSD存储基本知识

    2024-05-10 01:42:02       31 阅读
  3. C++学习笔记(多线程)

    2024-05-10 01:42:02       31 阅读
  4. Vuex存储数据实例

    2024-05-10 01:42:02       35 阅读
  5. SSH免密登录

    2024-05-10 01:42:02       31 阅读
  6. baxter机械臂校准

    2024-05-10 01:42:02       30 阅读