我正在寻找一个相当于 doReturn(...).when(...).*
我正在编写一些涉及大量系统类的单元测试(测试合同),因此需要拦截我无法控制的方法并返回一些回调(代码中的方法最终会返回)。在模拟中,我可以做类似 doReturn(...).when(...).*
我无法在 mockK 中找到类似的东西。似乎 every{} 总是在回答或返回之前运行该块。
class Vehicle: Listener {
fun displayCar(listener:Listener){
OtherClass().fetchCar(listener)
}
override fun showCarSuccessful() {
//do something
}
}
class OtherClass {
//assume its an outside function that returns nothing but invokes a method of listener call back
fun fetchCar(listener: Listener) {
//... Some system level operations that I don't have control to generate mock objects but in the test I want to use the listener to call some method so that I can
// test some contracts
listener.showCarSuccessful()
}
}
class Tests {
@Test
fun testCarSuccess() {
val listener: Listener = mockk(relaxed = true)
val vehicle = Vehicle()
//also tried with mockkClass and others
val other: OtherClass = mockk(relaxed = true)
every { other.fetchCar(listener) } returns {listener.showCarSuccessful()}
vehicle.displayCar(listener)
//do some verification checks here
}
}
interface Listener {
fun showCarSuccessful()
}