Mockk: With mockk(relaxed = true), default returned value of Pair is null

Created on 3 Oct 2020  路  4Comments  路  Source: mockk/mockk

Prerequisites

Please answer the following questions for yourself before submitting an issue.

  • [x] I am running the latest version
  • [x] I checked the documentation and found no answer
  • [x] I checked to make sure that this issue has not already been filed

Expected Behavior

When I mock an object with mockk(relaxed = true), I expect its method which has returned is Pair type will have non-null data inside.

Current Behavior

When I mock an object with mockk(relaxed = true), I notice its method which has returned is Pair type will have null data inside.

Steps to Reproduce

Please provide detailed steps for reproducing the issue.

private val data: DataObject = mockk(relaxed = true)
...
// later get data
val pairData: Pair<Boolean, String> = data.getPairData()
println(pairData) // Will be Pair(null,null), but I expect to Pair(false, "")

Context

Please provide any relevant information about your setup. This is important in case the issue is not reproducible except for under certain conditions.

  • MockK version: 1.10.0
  • Kotlin version: 1.3.72
  • JUnit version: 4.12
  • Type of test: Unit Test

All 4 comments

Yep this makes sense, it's somewhat similar to #386.

I'll try having a look into it.

Thanks @Raibaz for your update.

Hi @anticafe, I had a look into this and it turns out the expected behavior cannot be achieved due to the JVM's type erasure, which happens both in Kotlin and in Java.

In short, at runtime Pair<Boolean, String> is actually resolved to Pair<*, *> and there is no way to determine the types of the parameters.

Kotlin has a way to determine it with reified type parameters, but they can be used only in inline functions, so they won't work in this case.

I guess the only way to obtain the behavior you expect is to explicitly define every { data.pairData } returns pairOf().

Hi @Raibaz Thanks for detailed explanation. For now I'm using the same workaroud like you said every { data.pairData } returns pairOf(). But later, I think better to create a data class with Boolean and String.
I'll close the ticket now.

Was this page helpful?
0 / 5 - 0 ratings