如何解决 Expecting code to raise a throwable unit test case for Exceptions?

How to resolve Expecting code to raise a throwable unit test case for Exceptions?

image 我正在尝试为这种情况编写测试用例,在此我期待 SQLIntegrityConstraintViolationException,我试图使用 assert 抛出的断言来断言相同但我收到断言错误正如期望代码引发 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);
}      

不完全确定你的问题是什么......但据我了解你正在尝试检查异常类型......所以在这种情况下你可以使用这个 assertTrue(异常 instanceOf DataTruncationException)

这是你的意思吗? 您可以添加一个 try catch 块,然后在 catch 块中断言它

try {
functionToCall()
} catch (Throwable ex) {
assertTrue(ex instanceof DataTruncationException)
}

您可以使用 AssertJ 库来解决您的问题,它看起来像

assertThatThrownBy(() -> testingMehtod())
                .hasMessage("Checked message")
                .isInstanceOf(SQLException.class);

或者您可以使用 junit 断言,例如

assertThrows(SQLException.class, () -> testingMehtod(), "Checked message");

了解使用此类测试的原因很重要。因此,开发人员正在检查方法 throws(或不抛出)执行期间的异常。

简单例子

假设我们有一个像

这样的方法
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
    }
});