简体   繁体   English

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

[英]How to check for java.lang.AssertionError (JUnit 5)

Suppose the following class 假设下面的类

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

Is it possible to check with JUnit 5 if the methodToTest() throws the error evoked by the assert statement? 是否可以使用JUnit 5检查methodToTest()抛出assert语句引发的错误?

I only found in the JUnit 5 doc the assertThrows , but it checks only for exceptions and not for errors. 我仅在JUnit 5文档中找到assertThrows ,但它仅检查异常,而不检查错误。

Asserts that execution of the supplied executable throws an exception of the expectedType and returns the exception. 断言所提供的可执行文件的执行将引发ExpectedType的异常并返回该异常。

How would a test case look like to check weather the error is thrown? 测试用例如何检查引发错误的天气?

Actually, with assertThrows you can check for all Throwable like Exception, RuntimeException and Error. 实际上,使用assertThrows可以检查所有 Throwable例如Exception,RuntimeException和Error。 The assert keyword throws an AssertionError, which is a Throwable. assert关键字将引发AssertionError,这是一个Throwable。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM