Sey*_*bol 3 testing unit-testing kotlin mockk
PS:代码将在 Koltin
例如,我的服务类可以执行某些操作并注入一些其他服务。
class MyService(
private val someOtherService: OtherService
) {
fun doSomething() {
someOtherService.someMethod("foo")
someOtherService.someMethod("bar")
someOtherService.someMethod("baz")
}
}
Run Code Online (Sandbox Code Playgroud)
这是我对模拟 OtherService 的 MyService 类的测试:
internal class MyServiceTest {
@MockkBean(relaxed = true)
private lateinit var someOtherService: OtherService
@Test
fun `my test description`() {
every { someOtherService.someMethod(any()) } just Runs
verify(exactly = 1) {
someOtherService.someMethod(
match {
it shouldBe "bar"
true
}
)
}
}
Run Code Online (Sandbox Code Playgroud)
结果,"bar"参数将是预期的,但将是"foo"参数,并且测试将失败。
原因:someOtherService.someMethod("foo")之前会调用someOtherService.someMethod("bar")。
但是,我想验证每个方法是否只调用了一次。我怎么能做到这一点?
你可以:
verifySequence {
someOtherService.someMethod("foo")
someOtherService.someMethod("bar")
someOtherService.someMethod("baz")
}
Run Code Online (Sandbox Code Playgroud)
它验证是否只为提到的模拟执行了指定的调用序列。
如果没有,您可以使用列表捕获参数并稍后验证值。
| 归档时间: |
|
| 查看次数: |
4827 次 |
| 最近记录: |