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
- Host: GitHub
- URL: https://github.com/michaelbukachi/mockkcallback
- Owner: michaelbukachi
- Created: 2018-07-25T07:17:28.000Z (almost 7 years ago)
- Default Branch: master
- Last Pushed: 2018-07-31T05:19:54.000Z (almost 7 years ago)
- Last Synced: 2025-04-07T03:42:35.007Z (2 months ago)
- Topics: android, kotlin, mocking, mockk, testing
- Language: Kotlin
- Homepage:
- Size: 135 KB
- Stars: 3
- Watchers: 1
- Forks: 4
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
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: BackgroundTasklateinit 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"]()
}
}
}```