kosi-libs / MocKMP

A mocking processor for Kotlin Multiplatform
https://kosi-libs.org/mockmp
MIT License
188 stars 12 forks source link

Question: how to work with mock properties? #33

Closed xpathexception closed 2 years ago

xpathexception commented 2 years ago

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?

xpathexception commented 2 years ago

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)
}
SalomonBrys commented 2 years ago

Version 1.9.0 published with the fix.