kosi-libs/MocKMP

Question: how to work with mock properties?

xpathexception opened this issue · 2 comments

For example, I have a class under test and a mock

interface Sample {
    var sampleProperty: String
}

class UnderTest(val sample: Sample) {
    fun writeValue(data: String) {
        sample.sampleProperty = data
    }

    fun readValue(): String {
        return sample.sampleProperty
    }
}

I would like to write a test for methods writeValue and readValue, for example:

class SampleTest : TestsWithMocks() {
    override fun setUpMocks() = injectMocks(mocker)

    @Mock
    lateinit var sample: Sample

    val testable: UnderTest by withMocks { UnderTest(sample) }

    @Test
    fun sampleWriteTest() {
        val data = "foo"
        testable.writeValue(data)
    }

    @Test
    fun sampleReadTest() {
        val data = testable.readValue()
    }
}

For now I'm getting MockSample.(get/set):sampleProperty has not been mocked error each time I run test.

How to properly write rules in this case?

Feels like I've figured out this puzzle:

@Test
fun sampleWriteTest() {
    val data = "foo"

    mocker.every { sample.sampleProperty = isAny() } returns Unit
    testable.writeValue(data)
    mocker.verify { sample.sampleProperty = data }
}

@Test
fun sampleReadTest() {
    val data = "foo"

    mocker.every { sample.sampleProperty } returns data
    val result = testable.readValue()
    assertEquals(data, result)
}

Version 1.9.0 published with the fix.