Running unit tests for LiveData with Jupiter on Android

Running unit tests for ViewModels on Android where you have LiveData objects can be tricky. It is very possible that you get this exception:

java.lang.RuntimeException: Method getMainLooper in android.os.Looper not mocked.

Creating a custom rule won’t work if you are using JUnit 5 (Jupiter). The proper way is to have an extension like this one:

import androidx.arch.core.executor.ArchTaskExecutor
import androidx.arch.core.executor.TaskExecutor
import org.junit.jupiter.api.extension.AfterEachCallback
import org.junit.jupiter.api.extension.BeforeEachCallback
import org.junit.jupiter.api.extension.ExtensionContext

class InstantExecutorExtension : BeforeEachCallback, AfterEachCallback {
    override fun beforeEach(context: ExtensionContext?) {
        ArchTaskExecutor.getInstance().setDelegate(object : TaskExecutor() {
            override fun executeOnDiskIO(runnable: Runnable) =
            override fun postToMainThread(runnable: Runnable) =
            override fun isMainThread(): Boolean = true

    override fun afterEach(context: ExtensionContext?) {

And then over the test class that you have, you have to add the following annotation:

class MainActivityViewModelTest { }

Ta-Da. This is all you need in order to test LiveData classes.

One thought on “Running unit tests for LiveData with Jupiter on Android

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s