Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Question: how to work with mock properties? #33

Closed
xpathexception opened this issue Jul 20, 2022 · 2 comments
Closed

Question: how to work with mock properties? #33

xpathexception opened this issue Jul 20, 2022 · 2 comments

Comments

@xpathexception
Copy link

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
Copy link
Author

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
Copy link
Member

Version 1.9.0 published with the fix.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants