Return type are not matched for some value classes

  Kiến thức lập trình

When mocking function returns some primitive value class, assertion failed.

I guess the reason is representation of value class. Are there any workarounds?

Version:

  • Kotlin: 1.9.23
  • MockK: 1.3.10
@JvmInline
value class LongValueClass(val value: Long)

@JvmInline
value class StringValueClass(val value: String)

interface ValueGetter {
    suspend fun getLong(): LongValueClass
    suspend fun getString(): StringValueClass
}

class ValueGetterTest {
    private val someClass = mockk<ValueGetter>()

    // --- Failed test
    @Test
    fun testLong() = runTest {
        coEvery { someClass.getLong() } returns LongValueClass(2)
        assertEquals(LongValueClass(2), someClass.getLong())
    }

    // --- Succeeded test
    @Test
    fun testString() = runTest {
        coEvery { someClass.getString() } returns StringValueClass("test")
        assertEquals(StringValueClass("test"), someClass.getString())
    }
}

This test finish unsuccessfully with this error:

Expected :LongValueClass(value=2)
Actual   :2

org.opentest4j.AssertionFailedError: expected: <LongValueClass(value=2)> but was: <2>

Whole reproducible project: https://github.com/k-ogawa-1988/kotlin-mockk-value-class

The reason your test for LongValueClass is failing is because when you’re asserting, you’re comparing the LongValueClass object itself to the primitive Long value returned by the mocked function.

@Test
fun testLong() = runTest {
    coEvery { someClass.getLong() } returns LongValueClass(2)
    assertEquals(LongValueClass(2), LongValueClass(someClass.getLong().value))
}

New contributor

Meher Khurana is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

LEAVE A COMMENT