为了测试我的代码,我必须创建一些额外的断言方法(用于赋值(。
这个检查可执行文件是否抛出预期的类型、不抛出任何内容、抛出错误的exceptionMessage或没有exceptionMessage。
这是我的代码thusfar,但我不知道如何处理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
没有失败时,它返回异常。您可以使用该异常进行额外检查