junit报assertexception,JUnit 5:抛出如何断言异常?

在JUnit5中,你可以利用assertThrows()来方便地测试多个方法是否抛出预期的异常。这种方法使得在同一个测试用例中验证多个异常变得简单。例如,你可以导入Assertions静态类,然后通过lambda表达式定义要测试的代码,再调用assertThrows(),传入预期的异常类和包含测试代码的lambda,从而实现异常断言。
摘要由CSDN通过智能技术生成

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

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.

解决方案

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.

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

...

@Test

void exceptionTesting() {

Executable closureContainingCodeToTest = () -> throw new IllegalArgumentException("a message");

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

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值