Search code examples
spring-bootkotlinjunit

Kotlin Junit error: class kotlin.Unit cannot be cast to class java.lang.Boolean


Setup: Springboot with Kotlin

Description: try to mock a java method, from a kotlin Junit test file

Error source code line:

 Mockito.`when`(workflowService.sendEvent(ArgumentMatchers.anyString(), ArgumentMatchers.anyString())).thenReturn(true)

Error message:

 class kotlin.Unit cannot be cast to class java.lang.Boolean 

 class kotlin.Unit cannot be cast to class java.lang.Boolean (kotlin.Unit is in unnamed module of loader 'app'; java.lang.Boolean is in module java.base of loader 'bootstrap')

Solution

  • My Solution: instead of ArgumentMatchers.anyString(), use ArgumentMatchers.any() E.g:

     Mockito.`when`(workflowService.sendEvent(ArgumentMatchers.any(), ArgumentMatchers.any()))
     .thenReturn(true)
    

    Because Java String arguments accepts also null, we can use ArgumentMatchers.any()