24

I've been using an observeForever() method as described here to test Room and LiveData for a while, and it has worked flawlessly. But when I changed to Android Studio 3.2 (or if it was the androidx refactoring, not sure), that method suddenly stopped working, throwing a

java.lang.IllegalStateException: Cannot invoke observeForever on a background thread

How can we fix this?

Algar
  • 5,734
  • 3
  • 34
  • 51
  • assert main thread checking has been added in new androidx library livedata class. I think it's no longer can be used in background thread. – Sayem Sep 25 '18 at 09:38

2 Answers2

44

I solved it by adding the rule InstantTaskExecutorRule. According to the docs it will

A JUnit Test Rule that swaps the background executor used by the Architecture Components with a different one which executes each task synchronously.

So one needs to add

@get:Rule
val instantTaskExecutorRule = InstantTaskExecutorRule()

to the test class for it to work. The Java equivalent would be

@Rule
public InstantTaskExecutorRule instantTaskExecutorRule = new InstantTaskExecutorRule();

You will also need to add

androidTestImplementation "androidx.arch.core:core-testing:2.0.0"

to your models build.gradle dependencies.

Algar
  • 5,734
  • 3
  • 34
  • 51
5

As a beginner to this approach, accepted answer was a little bit vague for me. So just trying to explain it

add this in your build.gradle

androidTestImplementation "androidx.arch.core:core-testing:2.0.0

Now we need to add rule on test function. Lets say that I have a test function writeAndReadCategory then it will look like this in kotlin

    @get:Rule
    val instantTaskExecutorRule = InstantTaskExecutorRule()
    @Test
    fun writeAndReadCategory() {
        ....
    }
Zohab Ali
  • 8,426
  • 4
  • 55
  • 63