javaspring-bootkotlinelvis-operator

Testing function call with elvis operator with Mockito in Kotlin


I am trying to test a Service for a spring boot application i am writing in Kotlin and I ran into the following problem:

When trying to test getPerson(uuid: UUID) which calls my PersonRepository (which is mocked with Mockito) internally the exception which comes after the function call on the repository is always thrown.

Is there a way to work around this? Or should I handle the throwing of the exception differently?

PersonServiceTest

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

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

PersonService

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

Solution

  • You have to specify what happens if findByUuid is called. Right now it returns null.

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

    In general it might be better to use mockk with Kotlin. There you can specify to return default values for all mocked functions of an object. e.g.: val personRepository = mockk<PersonRepository>(relaxed = true)