我不确定如何在 kotlin 中模拟链接调用存储库
假设我有这项服务....
@Service
class FooService @Autowired constructor(
private val denmarkRepository: DenmarkRepository,
private val swedenRepository: SwedenRepository,
) {
fun getFoo(id: UUID): List<Currency> {
val currentDateTime = ZonedDateTime.now()
val result1 =
denmarkRepository.findById(id, currentDateTime)?.let { result ->
countryRepository.findCurrencyWithIdAndTime(
result.defaultSelection.id,
currentDateTime
)?.let { currency -> CurrencyDto(...) }
}
val result2 =
swedenRepository.findById(id, currentDateTime)?.let { result ->
countryRepository.findCurrencyWithIdAndTime(
result.defaultSelection.id,
currentDateTime
)?.let { currency -> CurrencyDto(...) }
}
}
return listOf(result1, result2)
}
...我想测试该功能
getFoo()
,我必须模拟K denmarkRepository.findById()
,countryRepository.findCurrencyWithIdAndTime()
和swedenRepository.findById()
。
every { denmarkRepository.findById(any<Long>(), any<ZonedDateTime>()) } returns denmark
every { swedenRepository.findById(any<Long>(), any<ZonedDateTime>()) } returns sweden
every { countryRepository.findCurrencyWithIdAndTime(any<Long>(), any<ZonedDateTime>()) } returns currency
但是,问题是
countryRepository.findCurrencyWithIdAndTime()
现在始终返回相同的值,因此 result1
和 result2
将始终相同。然而,这个return listOf(result1, result2)
在现实生活中却有着不同的价值观。
我如何模拟对存储库的链式调用,以便测试返回不同的值,即使它是相同的函数?
您可以使用
returnsMany
返回期望值列表
every { countryRepository.findCurrencyWithIdAndTime(any<Long>(), any<ZonedDateTime>()) }
returnsMany listOf(currency1,currency2)
另一种方法是与
andThen
链接
every { countryRepository.findCurrencyWithIdAndTime(any<Long>(), any<ZonedDateTime>()) }
returns currency1 andThen currency2