Testing Suspending Functions
Explore how to test Kotlin suspending functions effectively by using fakes and assertions without external libraries. Understand testing time-dependent coroutine behavior by simulating delays with virtual time and using kotlinx-coroutines-test tools like StandardTestDispatcher and TestCoroutineScheduler. Gain hands-on knowledge to write fast and reliable unit and integration tests for coroutines in Kotlin.
We'll cover the following...
Testing suspending functions in most cases is not different from testing normal functions. Take a look at the fetchUserData below from FetchUserUseCase. Checking whether it shows data, as expected, can be easily achieved thanks to a few fakes (or mocks) and simple assertions.
A fake class implements an interface, but contains fixed data and no logic. They help mimic a concrete behavior for testing.
Mocks are universal simulated objects that mimic the behavior of real objects in controlled ways. We generally create them using libraries, like MockK, which support mocking suspending functions. In the examples below, we have decided to use fakes to avoid using an external library.
Note: The example below will only throw an exception when both values passed to ...