Skip to content

michaelbukachi/MockkCallback

Repository files navigation

Testing Asynchronous Callbacks in Kotlin

Code snippet:


class ConsumerTest {

    @MockK(relaxUnitFun = true) // In order to avoid the strict check by Mockk, a relaxed mock is required
    lateinit var task: BackgroundTask

    lateinit var consumer: Consumer

    lateinit var spyConsumer: Consumer

    val callbackSlot = slot<Callback>()

    @Before
    fun setup() {
        MockKAnnotations.init(this)
        consumer = Consumer(task)
        spyConsumer = spyk(consumer, recordPrivateCalls = true)
    }

    @Test
    fun `test success`() {
        // Handle what happens when task.doBackground... is called
        // Capture callback and trigger it with the necessary data
        every { task.doBackground(capture(callbackSlot)) } answers {
            callbackSlot.captured.onDone(true, null)
        }

        spyConsumer.doBackgroundTask()

        verifyOrder {
            spyConsumer["printStarting"]()
            spyConsumer["printSuccess"]()
        }
    }

    @Test
    fun `test failure`() {
        every { task.doBackground(capture(callbackSlot)) } answers {
            callbackSlot.captured.onDone(false, null)
        }

        spyConsumer.doBackgroundTask()

        verifyOrder {
            spyConsumer["printStarting"]()
            spyConsumer["printFailed"]()
        }
    }
}

About

A tutorial on testing Java 8 callbacks using kotlin

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published