Kotlin Coroutines in Android — Unit Test

How to test our coroutines in a correct way?

Evan Fang
The Startup

--

We all know unit tests are important and necessary, and we also know we don’t really like to write it 😝. There are plenty of reasons that prevent us from writing good unit tests. The most likely situation I refuse to write it is that it often costs me double to triple time than to develop the main feature. After developing Android apps for 5~6 years, I found the main reasons resulting in that could be classified into two reasons:

  1. There is a high coupling in my code.
  2. I don’t really know how to write unit tests of my production code.

For the coupling problem, sometimes we find that it’s really hard to write the tests since the class has ambiguous duties or a high dependency on other classes. There are too many things about that, we need to clarify every class’s duty, try to create an interface to separate them and so on. But that’s not the topic we’re going to talk about in this post. Today, we’ll talk about the second problem: how to write unit tests of the Kotlin Coroutines code in an appropriate way.

Import library

Before we get started, remember to add the following code to your app/build.gradle as a test dependency:

dependencies {…

--

--

Evan Fang
The Startup

An Android/Flutter engineer at LINE Corporation.