繁体   English   中英

在 Kotlin 中使用带有 Mockito 的 elvis 操作员测试 function 调用

[英]Testing function call with elvis operator with Mockito in Kotlin

我正在尝试为我在 Kotlin 中编写的 spring 启动应用程序测试服务,但遇到了以下问题:

当尝试在内部测试调用我的 PersonRepository(用 Mockito 模拟)的getPerson(uuid: UUID)时,总是抛出在存储库上调用 function 之后出现的异常。

有没有办法解决这个问题? 或者我应该以不同的方式处理抛出异常?

人员服务测试

@Test
fun getPersonTest() {
    val uuid = UUID.randomUUID()
    personService.getPerson(uuid)

    val uuidArgumentCaptor = ArgumentCaptor.forClass(UUID::class.java)
    verify(personRepository).findByUuid(uuidArgumentCaptor.capture())
}

人员服务

fun getPerson(uuid: UUID): Person = personRepository.findByUuid(uuid) ?: throw PersonException("not found")

您必须指定调用 findByUuid 时会发生什么。 现在它返回 null。

Mockito.`when`(personRepository.findByUuid(uuid)).thenReturn(myFakePerson)

一般来说,最好将mockk与 Kotlin 一起使用。 您可以在此处指定为 object 的所有模拟函数返回默认值。 例如: val personRepository = mockk<PersonRepository>(relaxed = true)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM