You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin中是否存在对应check方法的assertAll类似实现?

Kotlin中是否有类似JUnit assertAll的多检查方法?

JUnit的assertAll方法可以批量执行所有断言,不会因为某一项失败就终止后续检查,示例代码如下:

assertAll(
    { assertEquals(a, b) },
    { assertEquals(c, d) },
)

你问的Kotlin里有没有类似checkAll的实现,能批量执行check检查、在多个条件不成立时输出所有错误信息——Kotlin标准库本身没有现成的checkAll方法,但可以自己快速实现一个,完全满足需求。

自定义实现checkAll

核心思路是:遍历所有检查逻辑,收集所有失败的错误信息,最后一次性抛出包含所有错误的异常,不会中途终止。

fun checkAll(vararg checks: () -> Unit) {
    val errorMessages = mutableListOf<String>()
    checks.forEach { checkBlock ->
        runCatching { checkBlock() }
            .onFailure { ex ->
                ex.message?.let { errorMessages.add(it) }
            }
    }
    if (errorMessages.isNotEmpty()) {
        throw IllegalStateException(errorMessages.joinToString("\n"))
    }
}

使用示例

val a = 1
val b = 2
val c = 3
val d = 4

checkAll(
    { check(a == b) { "error 1" } },
    { check(c == d) { "error 2" } }
)

当两个条件都不成立时,会抛出IllegalStateException,异常消息为:

error 1
error 2

另外,如果是在测试场景中,也可以直接用JUnit 5的assertAll(Kotlin完全兼容),它的行为和你要的类似,只是抛出的是AssertionError而非IllegalStateException:

assertAll(
    { assertEquals(a, b, "error 1") },
    { assertEquals(c, d, "error 2") }
)

内容的提问来源于stack exchange,提问作者vi0

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 00:43:17