Unit Testing In Android — Testing Coroutines using TestScope

Sarah Maher
2 min readOct 16, 2022

--

Photo by Mathew Schwartz on Unsplash

So you have started using coroutines in your codebase and you want to start writing tests to verify them. In this article we’ll be going through how to test a simple suspend function.

This Article assumes you have basic knowledge of Mockito and Unit Testing.

We will write our test to cover our class NewsFeed that have a simple suspend function that will give us a the count of the news headlines.

Let’s prepare our test!

When testing a suspend function we will need to prep your test class to support the coroutines.

The Needed Dependency :

we will add the following dependency into our gradle file:

A scope to run our tests in:

We need a scope to run our test in. I will use TestScope that will provide us with a coroutine scope that for launching test coroutines.

At the time of writing this article TestScope is experimental in coroutines API, which means that the design of the corresponding declarations has open issues which may (or may not) lead to their changes in the future. hence the @ExperimentalCoroutinesApi annotation

Lets Add the need the needed setup for the test :

We need to create an instance of the system under test , in this case NewsFeedClass. and here how our test class will look :

Our First Coroutine Test :

Our first test will cover the case when the function is successful and in this case we expect a list of headlines to contain 3 headlines.

Mocking the response

we will mock the response of the success case in the API to be able to test our function in isolation of the API.

In order to write a testable code we need to emphasize the importance of DI to be able to isolate our test.

We will add the following function, utilizing Mockito to return a dummy list whenever the getSomeApiResult gets triggered

Arrange.. Act .. Assert

Since all of our methods are suspending, will we use the testScope we defined to run them

Run the test now, and you will have your first coroutine test working!

Let’s Make it better!

since we may run into delay’s inside coroutines, testScope provides a bonus function advanceTimeBy( ), so there is no need to wait for the delay time inside your test!

Now you can run the test, write more of it, cover all the cases!

Thanks for reading!

--

--

Sarah Maher

An Engineer Who Keeps talking about Android || Women In Tech || Find me on LinkedIn : https://www.linkedin.com/in/sarah-maher-awad/