簡體   English   中英

測試是否拋出異常 - java

[英]test if exception was thrown - java

我有以下代碼(拋出異常的部分顯然是 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);
}

我的目標是測試異常是否被拋出,但是當我試圖從異常中獲取消息時,該值為 null- 意味着異常不包含消息。

我究竟做錯了什么?

嘗試這個:

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

如果這不起作用,請檢查 class SourceHostUnknownException是否將構造函數參數正確設置為超級消息字段

例如,如果您創建自定義異常 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