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) = runnable.run()
            override fun postToMainThread(runnable: Runnable) = runnable.run()
            override fun isMainThread(): Boolean = true
        })
    }

    override fun afterEach(context: ExtensionContext?) {
        ArchTaskExecutor.getInstance().setDelegate(null)
    }
}

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

@ExtendWith(InstantExecutorExtension::class)
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:

WordPress.com Logo

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

Facebook photo

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

Connecting to %s