Testing coroutines with runTest
📖 Scenario: You are writing a simple Kotlin function that uses coroutines to simulate a delayed greeting. You want to test this function properly using runTest from the Kotlin coroutines testing library.
🎯 Goal: Build a coroutine function that returns a greeting after a delay, then write a test using runTest to verify it returns the expected greeting.
📋 What You'll Learn
Create a suspend function called
delayedGreeting that returns a String after a 100ms delayUse
delay(100) inside the function to simulate workWrite a test function called
testDelayedGreeting using runTestInside the test, call
delayedGreeting and assert the returned value is exactly "Hello, Coroutine!"Print the test result string to the console
💡 Why This Matters
🌍 Real World
Testing coroutine functions is important in Android apps and backend services where asynchronous code is common.
💼 Career
Knowing how to test coroutines with <code>runTest</code> is a valuable skill for Kotlin developers working on reliable, maintainable asynchronous code.
Progress0 / 4 steps