paint-brush
Testing LiveData on Androidby@alediaferia
1,549 reads
1,549 reads

Testing LiveData on Android

by Alessandro DiaferiaDecember 17th, 2018
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

I’ve recently started to build an Android app to keep motivated on my journey to learn <a href="https://kotlinlang.org/" target="_blank">Kotlin</a>. My most recent experience has been with <a href="https://developer.android.com/topic/libraries/architecture/" target="_blank">Architecture Components</a> and this brief blog post, in particular, will focus on unit testing your DAO when using <code class="markup--code markup--p-code"><a href="https://developer.android.com/jetpack/arch/livedata" target="_blank">LiveData</a></code>.

People Mentioned

Mention Thumbnail

Company Mentioned

Mention Thumbnail
featured image - Testing LiveData on Android
Alessandro Diaferia HackerNoon profile picture

Testing LiveData represents an interesting challenge due to the peculiarities of its technology and the way it eases development for your Android app.

I’ve recently started to build an Android app to keep motivated on my journey to learn Kotlin. My most recent experience has been with Architecture Components and this brief blog post, in particular, will focus on unit testing your DAO when using [LiveData](https://developer.android.com/jetpack/arch/livedata).

What is LiveData?

LiveData is a lifecycle-aware, observable data holder that will help you react to changes in you data source. In my case, I'm using it in combination with [Room](https://developer.android.com/jetpack/arch/room) to make sure my app reacts to the new data becoming available in my database.

Our simple DAO

For this blog post let’s just pretend we have a very simple DAO that looks like the following:

This is just a DAO that helps you fetch posts.

As you can see, the return type for the function is not just a plain List<Post> but it wraps it in a [LiveData](https://developer.android.com/reference/android/arch/lifecycle/LiveData) instance. This is great because we can get an instance of our list of posts once and then observe for changes and react to them.

Let’s test it

The Android Developer documentation has a neat example on how to unit test your DAO:

This pretty simple test has the aim of testing that the data is being exposed correctly and that, once the post is added to the database, it is reflected by the getAll() invocation.

Unfortunately, by the time we are asserting on it, the value of the LiveData instance will not be populated and will make our test fail. This is because LiveData uses a lifecycle-oriented asynchronous mechanism to populate the underlying data and expects an observer to be registered in order to inform about data changes.

Observe your data

LiveData offers a convenient observe method that allows for observing the data as it changes. We can use it to register an observer that will assert on the expected value.

The observe method has the following signature:

void observe(LifecycleOwner owner, Observer<T> observer)

It expects an observer instance and the owner for its life-cycle. In our case, we’re only interested in keeping the observer around just enough to be able to assert on the changed data. We don’t want the same assertion to be evaluated every time the data changes.

Own your lifecycle

What we can do, then, is build an observer instance that owns its own life-cycle. After handling the onChange event we will mark the observer life-cycle as destroyed and let the framework do the rest.

Let’s see what the observer code looks like:

This observer implementation accepts a lambda that will be executed as part of the onChange event. As soon as the handler is complete, its own lifecycle will proceed to mark itself as _ON_DESTROY_ which will trigger the removal process from the LiveData instance.

We can then create an extension on LiveData to leverage this kind of observer:

fun <T> LiveData<T>.observeOnce(onChangeHandler: (T) -> Unit) {     val observer = OneTimeObserver(handler = onChangeHandler)     observe(observer, observer)}

Let’s test it again

A couple of things to notice this time.

First of all, we’re taking advantage of an [InstantTaskExecutorRule](https://developer.android.com/reference/androidx/arch/core/executor/testing/InstantTaskExecutorRule). This is a helpful utility rule that takes care of swapping the background asynchronous task executor with a synchronous one. This is vital to be able to deterministically test our code. (Check this out if you wanna know more about JUnit rules).

In addition to that, we’re now leveraging the LiveData extension that we have written to write our assertions:

postDao.getAll().observeOnce {    assertEquals(0, it.size)}

We have just asserted in a much more compact and expressive way by leaving all the details inside our observer implementation. We are now asserting on the LiveData instance in a deterministic way making this kind of tests easier to read and write.

Conclusion

I hope this post will help you write tests for your DAO more effectively. This is one of my earliest experiences with Kotlin and Android: please, feel free to comment with better approaches to solve this.

Cover photo by Irvan Smith on Unsplash