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

问题描述 投票:1回答:1

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

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

在Java中,如果我想将可执行文件的声明与执行本身分开,为了澄清Given-Then-When形式的测试,我们可以像这样使用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) }
}

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

exception kotlin lambda junit5 assertion
1个回答
4
投票

只需像在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)
}
© www.soinside.com 2019 - 2024. All rights reserved.