Unit testing suspending functions
In this section, we will focus on how you can unit test your suspending functions. You can create unit tests for classes such as ViewModel
that launch a coroutine or have suspending functions.
Creating a unit test for a suspending function is more difficult to write as a suspending function can only be called from a coroutine or another coroutine. What you can do is use the runBlocking
coroutine builder and call the suspending function from there. For example, say you have a MovieRepository
class like the following:
class MovieRepository (private val movieService:
MovieService) {
...
private val movieLiveData =
MutableLiveData<List<Movie>>()
fun fetchMovies() {
...
val movies = movieService.getMovies...