An open API service indexing awesome lists of open source software.

https://github.com/michaelbukachi/mockkcallback

A tutorial on testing Java 8 callbacks using kotlin
https://github.com/michaelbukachi/mockkcallback

android kotlin mocking mockk testing

Last synced: about 1 month ago
JSON representation

A tutorial on testing Java 8 callbacks using kotlin

Awesome Lists containing this project

README

        

## 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()

@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"]()
}
}
}

```