测试是否抛出异常 - 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);
}
我的目标是测试是否引发了异常,但是当我尝试从异常中获取消息时,该值为空,这意味着异常不包含消息。
我做错了什么?
I have the following code (the part that throws the exception is obviously part of a class but I only put the relevant lines).
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);
}
My goal is to test if the exception was thrown, but when I'm trying to get the message from the exception, the value is null- meaning, the exception doesn't contain the message.
What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
试试这个:
如果这不起作用,请检查类
SourceHostUnknownException
是否将构造函数参数正确设置到超级消息字段中,例如,如果您创建自定义异常类并定义构造函数,则需要传递发送给 super 的字符串消息,因为您期望 getMessage() 方法返回错误消息。
Try this:
And if this does not work, check if the class
SourceHostUnknownException
is setting the constructor parameter correctly into super message fieldfor example, if you create custom exception class and you define constructor you need to pass the String message to super, as you are expecting getMessage() method to return you the error message.