简体   繁体   English

测试是否抛出异常 - java

[英]test if exception was thrown - java

I have the following code (the part that throws the exception is obviously part of a class but I only put the relevant lines).我有以下代码(抛出异常的部分显然是 class 的一部分,但我只放了相关行)。

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.我的目标是测试异常是否被抛出,但是当我试图从异常中获取消息时,该值为 null- 意味着异常不包含消息。

What am I doing wrong?我究竟做错了什么?

Try this:尝试这个:

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

And if this does not work, check if the class SourceHostUnknownException is setting the constructor parameter correctly into super message field如果这不起作用,请检查 class SourceHostUnknownException是否将构造函数参数正确设置为超级消息字段

for 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.例如,如果您创建自定义异常 class 并定义构造函数,您需要将 String 消息传递给 super,因为您希望getMessage()方法返回错误消息。

public class SourceHostUnknownException extends Exception {

public SourceHostUnknownException(String message) {
    super(message);
}
}

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

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