如何检查 mockk Mock 的构造函数参数?
How can I check the constructur arguments of a mockk Mock?
我有以下代码(在 Kotlin 中):
class X {
fun foo() {
val A(1, true, "three")
val b = B()
b.bar(A)
}
}
我想要的是找出 A
实例化的内容。
我的测试代码是这样的:
// Needed for something else
every { anyConstructed<A>().go() } returns "testString"
// What I'm using to extract A
val barSlot = slot<A>()
verify { anyConstructed<B>().bar(capture(barSlot)) }
val a = barSlot.captured
我如何检查 A
实例化了哪些值,现在我已经设法捕获了在构建时创建的模拟(感谢 every
语句)?
谢谢!
您可以通过两种方式完成:
使用slot
获取参数:
@Test
fun shouldCheckValuesAtConstruct() {
val a = A(1, true, "s")
val b = mockk<B>()
val aSlot = slot<A>()
every { b.bar(a = capture(aSlot)) } returns Unit
b.bar(a)
val captured = aSlot.captured
assertEquals(1, captured.a)
assertEquals(true, captured.b)
assertEquals("s", captured.s)
}
或使用withArg
函数和内联断言
@Test
fun shouldCheckValuesAtConstructInlineAssertion() {
val a = A(1, true, "s")
val b = mockk<B>()
every { b.bar(a) } returns Unit
b.bar(a)
verify {
b.bar(withArg {
assertEquals(1, it.a)
assertEquals(true, it.b)
assertEquals("s", it.s)
})
}
}
我有以下代码(在 Kotlin 中):
class X {
fun foo() {
val A(1, true, "three")
val b = B()
b.bar(A)
}
}
我想要的是找出 A
实例化的内容。
我的测试代码是这样的:
// Needed for something else
every { anyConstructed<A>().go() } returns "testString"
// What I'm using to extract A
val barSlot = slot<A>()
verify { anyConstructed<B>().bar(capture(barSlot)) }
val a = barSlot.captured
我如何检查 A
实例化了哪些值,现在我已经设法捕获了在构建时创建的模拟(感谢 every
语句)?
谢谢!
您可以通过两种方式完成:
使用slot
获取参数:
@Test
fun shouldCheckValuesAtConstruct() {
val a = A(1, true, "s")
val b = mockk<B>()
val aSlot = slot<A>()
every { b.bar(a = capture(aSlot)) } returns Unit
b.bar(a)
val captured = aSlot.captured
assertEquals(1, captured.a)
assertEquals(true, captured.b)
assertEquals("s", captured.s)
}
或使用withArg
函数和内联断言
@Test
fun shouldCheckValuesAtConstructInlineAssertion() {
val a = A(1, true, "s")
val b = mockk<B>()
every { b.bar(a) } returns Unit
b.bar(a)
verify {
b.bar(withArg {
assertEquals(1, it.a)
assertEquals(true, it.b)
assertEquals("s", it.s)
})
}
}