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

如何在Kotlin中使用MockK让仓储链式调用返回不同模拟值?

MockK配置同一仓储方法多次调用返回不同模拟结果

你的问题根源在于对countryRepository.findCurrencyWithIdAndTime的Mock配置过于宽泛(比如用any()匹配所有参数),导致无论传入丹麦还是瑞典的地区ID,都返回相同值。可以通过以下两种方式解决:

1. 按参数匹配返回对应结果(推荐,贴合业务逻辑)

针对不同的地区ID参数,单独配置Mock返回值,确保不同地区调用时返回对应货币数据:

// 初始化各依赖的Mock实例
val denmarkRepo = mockk<DenmarkRepository>()
val swedenRepo = mockk<SwedenRepository>()
val countryRepo = mockk<CountryRepository>()
val fooService = FooService(denmarkRepo, swedenRepo, countryRepo)

// 模拟地区Repository返回对应ID
every { denmarkRepo.findById(any()) } returns Denmark(id = "DK")
every { swedenRepo.findById(any()) } returns Sweden(id = "SE")

// 关键:为不同地区ID配置不同的货币返回值
every { countryRepo.findCurrencyWithIdAndTime("DK", any()) } returns "DKK"
every { countryRepo.findCurrencyWithIdAndTime("SE", any()) } returns "SEK"

// 执行测试并验证结果
val fooResult = fooService.getFoo()
assertEquals("DKK", fooResult.denmarkCurrency)
assertEquals("SEK", fooResult.swedenCurrency)

2. 按调用顺序指定返回值

如果是同一参数需要多次调用返回不同结果(比如同一地区多次查询返回更新后的数据),可以用andThen链式配置返回序列:

// 同一参数第一次调用返回DKK,第二次返回更新后的DKK_updated
every { countryRepo.findCurrencyWithIdAndTime("DK", any()) } returns "DKK" andThen "DKK_updated"

注意:你的业务场景更适合第一种参数匹配的方式,因为本质是不同地区参数对应不同业务结果,而非同一参数的多次调用差异。

内容的提问来源于stack exchange,提问作者four-eyes

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 11:17:19