在带有JUnit5的Kotlin中,我们可以使用assertFailsWith

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

在Java中,如果我想将可执行文件的声明与执行本身分开,为了澄清“给定时间”形式的测试,我们可以像这样使用JUnit5 assertThrows:

@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);
}

在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) }
}

但是,如何使用assertFailsWith将Kotlin中的声明和执行分开?

最佳答案

就像在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)
}

09-25 16:29