JUnit 5:如何断言抛出异常? [英] JUnit 5: How to assert an exception is thrown?

查看:56
本文介绍了JUnit 5:如何断言抛出异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 JUnit 5 中是否有更好的方法来断言某个方法抛出异常?

Is there a better way to assert that a method throws an exception in JUnit 5?

目前,我必须使用 @Rule 来验证我的测试是否抛出异常,但这不适用于我希望多个方法在我的测试中抛出异常的情况.

Currently, I have to use an @Rule in order to verify that my test throws an exception, but this doesn't work for the cases where I expect multiple methods to throw exceptions in my test.

推荐答案

您可以使用 assertThrows(),它允许您在同一范围内测试多个异常测试.由于支持 Java 8 中的 lambda,这是在 JUnit 中测试异常的规范方法.

You can use assertThrows(), which allows you to test multiple exceptions within the same test. With support for lambdas in Java 8, this is the canonical way to test for exceptions in JUnit.

根据 JUnit 文档:>

import static org.junit.jupiter.api.Assertions.assertThrows;

@Test
void exceptionTesting() {
    MyException thrown = assertThrows(
           MyException.class,
           () -> myObject.doThing(),
           "Expected doThing() to throw, but it didn't"
    );

    assertTrue(thrown.getMessage().contains("Stuff"));
}

这篇关于JUnit 5:如何断言抛出异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆