kotlin + junit 5-assertAll用法

use*_*282 3 kotlin junit5

我使用下一个版本的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>
Run Code Online (Sandbox Code Playgroud)

Kotlin版本是

    <kotlin.version>1.2.31</kotlin.version>
Run Code Online (Sandbox Code Playgroud)

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

assertAll("person",
    { assertEquals("John", person.firstName) },
    { assertEquals("Doe", person.lastName) }
)
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)

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

assertAll("person",
    Executable { assertEquals("John", person.firstName) },
    Executable { assertEquals("Doe", person.lastName) }
)
Run Code Online (Sandbox Code Playgroud)

Jay*_*ard 11

使用Kotlin函数assertAll()而不是static函数Assertions.assertAll(),您会很高兴的。从以下位置更改导入:

import org.junit.jupiter.api.Assertions.assertAll
Run Code Online (Sandbox Code Playgroud)

至:

import org.junit.jupiter.api.assertAll
Run Code Online (Sandbox Code Playgroud)

现在,此代码将起作用:

assertAll("person",
    { assertEquals("John", person.firstName) },
    { assertEquals("Doe", person.lastName) }
)
Run Code Online (Sandbox Code Playgroud)

您可能会想知道JUnit 5直接来自JUnit团队,其主要源代码中包含Kotlin帮助器!

如果您确实真的要使用Java的纯文本版本,则需要输入Lambda:

assertAll("person",
    Executable { assertEquals("John", person.firstName) },
    Executable { assertEquals("Doe", person.lastName) }
)
Run Code Online (Sandbox Code Playgroud)