Kotlin 和 JUnit 5 断言抛出异常:使用 assertFailsWith 单独声明和执行

p3q*_*uod 6 lambda exception assertion kotlin junit5

在科特林与JUnit5我们可以使用assertFailsWith

在带有 JUnit5 的 Java 中,您可以使用assertThrows

在 Java 中,如果我想将可执行文件的声明与执行本身分开,为了以 Given-Then-When 形式阐明测试,我们可以assertThrows像这样使用 JUnit5 :

@Test
@DisplayName("display() with wrong argument command should fail" )
void displayWithWrongArgument() {

    // Given a wrong argument
    String arg = "FAKE_ID"

    // When we call display() with the wrong argument
    Executable exec = () -> sut.display(arg);

    // Then it should throw an IllegalArgumentException
    assertThrows(IllegalArgumentException.class, exec);
}
Run Code Online (Sandbox Code Playgroud)

在 Kotlin 中,我们可以使用assertFailsWith

@Test
fun `display() with wrong argument command should fail`() {

    // Given a wrong argument
    val arg = "FAKE_ID"

    // When we call display() with the wrong argument
    // ***executable declaration should go here ***

    // Then it should throw an IllegalArgumentException
    assertFailsWith<CrudException> { sut.display(arg) }
}
Run Code Online (Sandbox Code Playgroud)

但是,我们如何将 Kotlin 中的声明和执行分开assertFailsWith

awe*_*oon 7

只需像在 Java 中一样声明一个变量:

@Test
fun `display() with wrong argument command should fail`() {

    // Given a wrong argument
    val arg = "FAKE_ID"

    // When we call display() with the wrong argument
    val block: () -> Unit = { sut.display(arg) }

    // Then it should throw an IllegalArgumentException
    assertFailsWith<CrudException>(block = block)
}
Run Code Online (Sandbox Code Playgroud)


san*_*adi 6

在我的例子中你可以这样做:

@Test
fun divide() {
    assertThrows(
        ArithmeticException::class.java,
        { MathUtils.divide(1, 0) },
        "divide by zero should trow"
    )
}
Run Code Online (Sandbox Code Playgroud)