在 Kotlin 中使用 Mockito 测试 elvis 运算符的函数调用
Testing function call with elvis operator with Mockito in Kotlin
我正在尝试为我用 Kotlin 编写的 spring 引导应用程序测试服务,我 运行 遇到以下问题:
当尝试测试 getPerson(uuid: UUID)
时,它会在内部调用我的 PersonRepository(用 Mockito 模拟),总是抛出在存储库上调用函数之后出现的异常。
有办法解决这个问题吗?或者我应该以不同的方式处理异常的抛出?
PersonServiceTest
@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 会发生什么。现在它 return 无效。
Mockito.`when`(personRepository.findByUuid(uuid)).thenReturn(myFakePerson)
一般来说,将 mockk 与 Kotlin 一起使用可能会更好。您可以在其中为对象的所有模拟函数指定 return 默认值。例如:val personRepository = mockk<PersonRepository>(relaxed = true)
我正在尝试为我用 Kotlin 编写的 spring 引导应用程序测试服务,我 运行 遇到以下问题:
当尝试测试 getPerson(uuid: UUID)
时,它会在内部调用我的 PersonRepository(用 Mockito 模拟),总是抛出在存储库上调用函数之后出现的异常。
有办法解决这个问题吗?或者我应该以不同的方式处理异常的抛出?
PersonServiceTest
@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 会发生什么。现在它 return 无效。
Mockito.`when`(personRepository.findByUuid(uuid)).thenReturn(myFakePerson)
一般来说,将 mockk 与 Kotlin 一起使用可能会更好。您可以在其中为对象的所有模拟函数指定 return 默认值。例如:val personRepository = mockk<PersonRepository>(relaxed = true)