exception - Kotlin 和 JUnit 5 断言抛出异常 : separate declaration and execution with assertFailsWith

标签 exception kotlin lambda junit5 assertion

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

但是,我们如何使用 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)
}

关于exception - Kotlin 和 JUnit 5 断言抛出异常 : separate declaration and execution with assertFailsWith,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55878003/

相关文章:

java - 从构造函数抛出未经检查的异常时面临 java.lang.StackOverflowError

java - 无法从任何地方构建 Hibernate SessionFactory 异常

通过 HTTP 代理的 Java TCP 数据包

android - 如何在编译时更改.kt或.java文件并通过.kt或.java构建进行构建

python - Django 重复输入键

android - Kotlin JaCoCo,无覆盖 -> IllegalClassFormatException ...请提供原始的非仪器类

对多列记录进行排序的 Pythonic 方式

使用值搜索 Java Map 的 Lambda 表达式

C++11 闭包 shared_ptr

android - Android:退出应用后,AlarmManager无法启动应用