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

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

问题描述

有没有更好的方法断言方法在JUnit 5中抛出异常?

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

目前,我必须使用@Rule来验证我的test抛出一个异常,但这对于我希望多个方法在我的测试中抛出异常的情况不起作用。

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中支持lambdas,这可能会成为在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 probably going to become the canonical way to test for exceptions in JUnit.

JUnit docs

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

...

@Test
void exceptionTesting() {
    Executable closureContainingCodeToTest = () -> throw new IllegalArgumentException("a message");

    assertThrows(IllegalArgumentException.class, closureContainingCodeToTest, "a message");
}

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

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