测试是否抛出异常-java



我有以下代码(抛出异常的部分显然是类的一部分,但我只放了相关的行(。

if (found==null)
{
log.warn("Got request from source IP - " + ip + " which is not in the env - not answering");
throw new SourceHostUnknownException("This command is only supported from within the Environment");
}

@Test
public void testSecurityResult_whenRVERegex_assertexception()
{
Throwable exception = Assertions.assertThrows(SourceHostUnknownException.class, () -> {
SecurityResult result = secSvc.validateRequest(req);
});
String expectedMessage = "This command is only supported from within the Environment";
String actualMessage = exception.getMessage();
Assertions.assertEquals(expectedMessage,actualMessage);
}

我的目标是测试是否抛出了异常,但当我试图从异常中获取消息时,值为null,这意味着异常不包含消息。

我做错了什么?

试试这个:

Assertions.assertThatExceptionOfType(SourceHostUnknownException.class).isThrownBy(() -> {
SecurityResult result = secSvc.validateRequest(req);
}).withMessage("This command is only supported from within the Environment");

如果这不起作用,请检查类SourceHostUnknownException是否将构造函数参数正确设置为超级消息字段

例如,如果创建自定义异常类并定义构造函数,则需要将String消息传递给super,因为您希望getMessage((方法返回错误消息。

public class SourceHostUnknownException extends Exception {
public SourceHostUnknownException(String message) {
super(message);
}
}

最新更新