gpt4 book ai didi

java - 如何检查 java.lang.AssertionError (JUnit 5)

转载 作者:行者123 更新时间:2023-12-02 02:30:58 24 4
gpt4 key购买 nike

假设有以下类

class classToTest{
public static void methodToTest() {
assert false: "error is thrown";
}
}

是否可以使用 JUnit 5 检查 methodToTest() 是否抛出由断言语句引起的错误?

我只在 JUnit 5 文档中找到了 assertThrows,但它仅检查异常而不检查错误。

Asserts that execution of the supplied executable throws an exception of the expectedType and returns the exception.

检查是否抛出错误的测试用例会是什么样子?

最佳答案

实际上,使用 assertThrows 您可以检查所有 Throwable,例如 Exception、RuntimeException 和 Error。 assert 关键字抛出一个 AssertionError,它是一个 Throwable。

AssertionError error = Assertions.assertThrows(AssertionError.class, () -> {
classToTest.methodToTest();
});
Assertions.assertEquals("error is thrown", error.getMessage());

关于java - 如何检查 java.lang.AssertionError (JUnit 5),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47121610/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com