如何用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
相关产品推荐
相关产品推荐

