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

如何用Kotest断言判断列表中存在满足指定属性匹配条件的元素

Kotest 对应实现方案

有两种常用实现方式,可根据使用场景选择:

1. 直接使用shouldAny扩展方法(最贴合需求写法)

这是Kotest提供的和AssertJ anySatisfy完全对等的API,写法和你给出的伪代码几乎一致:

import io.kotest.matchers.collections.shouldAny

// 直接传入断言块,只要有一个元素满足块内所有断言就通过
cars.shouldAny { car ->
    car.colour shouldBe pet.colour
    car.owner shouldBe pet.owner
}

注:该API在Kotest 5.0+版本的kotest-assertions-core依赖中提供,是一次性校验场景的首选方案。

2. 自定义匹配器(适合复用场景)

如果该属性匹配逻辑需要在多处使用,可以提前定义匹配器,配合shouldContain使用:

import io.kotest.matchers.Matcher
import io.kotest.matchers.MatcherResult
import io.kotest.matchers.collections.shouldContain

// 定义可复用的匹配规则
fun matchesPetCommonAttributes(pet: Pet) = Matcher<Car> { car ->
    MatcherResult(
        passed = car.colour == pet.colour && car.owner == pet.owner,
        failureMessageFn = { "Car(colour=${car.colour}, owner=${car.owner}) 未匹配 Pet(colour=${pet.colour}, owner=${pet.owner})" },
        negatedFailureMessageFn = { "Car(colour=${car.colour}, owner=${car.owner}) 意外匹配 Pet(colour=${pet.colour}, owner=${pet.owner})" }
    )
}

// 调用断言
cars.shouldContain(matchesPetCommonAttributes(pet))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 06:24:04