如何解决期望代码以引发异常的可抛出单元测试用例?
像 我试图写测试用例这种情况下,在此我期待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在我看来,使用更有趣。