kotlin + junit 5 -assertAll 用法

标签 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>

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 在其主要源代码中包含直接来自 JUnit 团队的 Kotlin 助手!

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

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

关于kotlin + junit 5 -assertAll 用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50491377/

相关文章:

java - 在测试中的 Spring 环境中使用 @EnabledIf 和 spring.profiles.active 属性

Kotlin 类型自动装箱 vs 原始类型

android - 如何通过 Intent 下载和安装 APK 文件?

maven - Javalin 教程产生 "Unresolved reference: AtomicInteger"

java - Kafka - 如何模拟消费者记录?

intellij-idea - java.lang.NoClassDefFoundError : org/junit/platform/launcher/TestExecutionListener

java - 如何长时间、以随机顺序、使用多个实例重复运行 junit 5 测试类?

java - 在 JUnit/Mockito 测试中使用 Mocked 对象

android - 如何在 Kotlin 上持续监听 UDP 数据

android - 带构造函数的房间类型转换器