kotlin + junit 5 - assertAll 用法

kotlin + junit 5 - assertAll usage

我使用下一个版本的 junit 5

    <junit.jupiter.version>5.2.0</junit.jupiter.version>
    <junit.platform.version>1.2.0</junit.platform.version>
    <junit.vintage.version>5.2.0</junit.vintage.version>

Kotlin 版本为

    <kotlin.version>1.2.31</kotlin.version>

我尝试将 junit 5 中的新断言功能与 kotlin 一起使用,例如

assertAll("person",
    { assertEquals("John", person.firstName) },
    { assertEquals("Doe", person.lastName) }
)

但是代码分析器说找不到合适的方法版本。

Error:(28, 9) Kotlin: None of the following functions can be called with the arguments supplied: 
    public fun assertAll(vararg executables: () -> Unit): Unit defined in org.junit.jupiter.api
    public fun assertAll(heading: String?, vararg executables: () -> Unit): Unit defined in org.junit.jupiter.api

如果我这样写代码,它就可以正常工作。有什么诀窍?

assertAll("person",
    Executable { assertEquals("John", person.firstName) },
    Executable { assertEquals("Doe", person.lastName) }
)

使用 Kotlin 函数 assertAll() 而不是静态函数 Assertions.assertAll() 你会很开心。更改导入自:

import org.junit.jupiter.api.Assertions.assertAll

至:

import org.junit.jupiter.api.assertAll

现在这段代码可以工作了:

assertAll("person",
    { assertEquals("John", person.firstName) },
    { assertEquals("Doe", person.lastName) }
)

您可能有兴趣知道 JUnit 5 在其主要源代码中包含 Kotlin 助手,直接来自 JUnit 团队!

如果您真的非常非常想使用直接 Java 版本,您需要输入您的 Lambda:

assertAll("person",
    Executable { assertEquals("John", person.firstName) },
    Executable { assertEquals("Doe", person.lastName) }
)