mockito / mockito-kotlin

Using Mockito with Kotlin
MIT License
3.1k stars 200 forks source link

Kotlin Result seems to behave weirdly when trying to be returned with Mockito #381

Closed adrianhescalante closed 4 years ago

adrianhescalante commented 4 years ago

I am facing an issue when trying to use the Kotlin Result in my project. I am trying to mock the return value as shown here:

`when`(useCase.getA()).thenReturn(Result.success(ObjectA("testName")))

The exception when trying to use that returned Result is this one: java.lang.ClassCastException: kotlin.Result cannot be cast to ObjectA

An interesting thing I found when debugging is that if I check the returned value of that useCase.getA() function, it returns an object with description Success(Success(ObjectA(name=testName))). A regular Result returns this description Success(ObjectA(name=name)). I guess that's the reason it's failing, it seems there is like a nested Result object, so I am assuming there is something wrong with Mockito when handling the Kotlin Result class.

This is a gist I created to test it. There are two tests, one with the Kotlin Result and another one with a quick Result implementation (OwnResult) to check there is not something wrong I am doing myself.

I am using Mockito 3.3.3 on an Android project with Java 8.

adrianhescalante commented 4 years ago

Sorry, I wanted to ask this in the mockito library, not in the mockito-kotlin, just an error.

bohsen commented 4 years ago

@adrianhescalante Result-class is an inline class. Mockito doesn't know how to handle this. Take a look at #309 and #363.

adrianhescalante commented 4 years ago

Thank you, @bohsen, good to know. What alternative would you use to handle results? Maybe Either?

bohsen commented 4 years ago

@adrianhescalante I've used this a lot.

adrianhescalante commented 4 years ago

Thanks, it looks good!