如何解决如何为异常消息创建断言
为了测试我的代码,我必须创建一些额外的断言方法(用于赋值)。
这个检查一个可执行文件是否抛出了expectedType、什么都不抛出、抛出了错误的exceptionMessage 或没有exceptionMessage。
这是我目前的代码,但我不知道如何处理异常消息检查。
public class Test {
public static void assertThrowsMessage(Class<? extends Exception> expectedType,Executable executable,String exceptionMessage,String message) {
//Throws AssertionError when wrong exception type is thrown
Assertions.assertThrows(
expectedType,() -> {throw new Exception();},message
);
//Throws AssertionError when no exception type is thrown
Assertions.assertThrows(
expectedType,() -> {},message
);
//Throws AssertionError when no exceptionMessage is thrown
Assertions.assertThrows(
);
//Throws AssertionError when wrong exceptionMessage is thrown
Assertions.assertThrows(
);
}
解决方法
您可以通过以下方式检查错误消息:
Throwable exception = Assertions.assertThrows(expectedType,() ->
{
throw new RuntimeException( "Error message" );
},message );
Assertions.assertEquals( expectedMessage,exception.getMessage(),message );
当 assertThrows
没有失败时,它返回异常。您可以使用该异常进行额外检查
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。