Testing Suspending Functions

Learn how to test suspending functions and get an overview of their time dependency.

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 assertEquals are different.

Get hands-on with 1400+ tech skills courses.