![](/img/trans.png)
[英]JUnit AssertionError: Expecting code to raise a throwable
[英]How to resolve Expecting code to raise a throwable unit test case for Exceptions?
圖像我正在嘗試為這種情況編寫測試用例,在這種情況下,我期待SQLIntegrityConstraintViolationException
,我試圖使用拋出的斷言斷言相同,但我收到斷言錯誤,因為期望代碼引發Throwable
。 如何解決這個問題,有人可以幫我解決這個問題。
我正在使用JUnit5
。
如屏幕截圖所示,應用異常情況后該方法似乎沒有運行
@Test
public void insertUpdateDatatypesizecountValidation() throws Exception {
id = 0;
StandAloneConnection standAloneConnection = new StandAloneConnection(
propertyFile);
Connection conn = standAloneConnection.getConnection();
assertThatThrownBy(() -> called.datas(conn, id))
.hasMessage("Column 'ID' cannot be null")
.isInstanceOf(SQLIntegrityConstraintViolationException.class);
}
您可以使用AssertJ
庫來解決您的問題,它看起來像
assertThatThrownBy(() -> testingMehtod())
.hasMessage("Checked message")
.isInstanceOf(SQLException.class);
或者您可以使用junit
斷言,例如
assertThrows(SQLException.class, () -> testingMehtod(), "Checked message");
了解使用此類測試的原因很重要。 因此,開發人員正在檢查方法在執行期間是否拋出(或不拋出)異常。
簡單的例子
假設我們有一個類似的方法
static void testMethod(String arg) {
Objects.requireNonNull(arg, "Argument cannot be null");
// some code to work
}
我們必須檢查它是否正常工作:
@Test
void someTest() {
assertThrows(NullPointerException.class,
() -> testMethod(null),
"Argument cannot be null");
assertDoesNotThrow(() -> testMethod("data"));
}
上述測試將通過。
下面的測試將因AssertionError
而失敗
@Test
void someTest1() {
assertThrows(IOException.class, () -> testMethod(null), "IO error");
}
@Test
void someTest2() {
assertThrows(NullPointerException.class,
() -> testMethod("data"),
"Argument cannot be null");
}
上面使用junit assertions
的示例。 在我看來,使用AssertJ
更有趣。
您可以使用:
Assertions.assertThrows(DataTruncation.class, new Executable() {
@Override
public void execute() throws Throwable {
//the code which you expect to throw this exception
}
});
不完全確定你的問題是什么......但據我所知,你正在嘗試檢查異常的類型......所以在這種情況下你可以使用這個 assertTrue(exception instanceOf DataTruncationException)
這就是你的意思嗎? 您可以添加一個 try catch 塊,然后在 catch 塊中斷言它
try {
functionToCall()
} catch (Throwable ex) {
assertTrue(ex instanceof DataTruncationException)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.