I am still learning kotlin, and I am curious how is it possible that mockk is able to return some object T
wrapped in Result<T>
. For better understanding let analyse below example:
We have such method definition
fun save(toSave : Entity): Result<Entity>
when we mock such method using returnArguments
like it is done below:
every { mocked.save(any()) } returnsArgument 0
Then method returns Result<Entity>
, but logic says that Entity
should be returned.
Looking into declaration of returnsArgument
there is casting to generic type which in our case is Result<Entity>
, but when I tried to do it in plain I had casting exception.
I assume some magic happens inside, but what magic is responsible for such thing?
Would it be done with any wrapping object or it is specific only to Result
?
CodePudding user response:
Result<T>
is a value class and mockk
has a value class support.
After many internal steps returnsArgument
will wrap the argument n
with the specified value class and will return it.
Would it be done with any wrapping object or it is specific only to Result?
All value classes are supported, not just Result<T>
.
// supported
@JvmInline
value class ValueWrapper<out T> (val something: Any?)
// not supported
class SomeWrapper<out T> (val something: Any?)
Hope it helps.