3

My local unit tests use LiveData all the time. Normally, when you try to set a value on MutableLiveData you get

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

because local JVM has no access to Android framework. I fixed that using that:

@get:Rule
val rule = InstantTaskExecutorRule()

Everything was fine, until I had to use PowerMockito to mock a static method from google play library. Since I added

@RunWith(PowerMockRunner::class)
@PrepareForTest(Tasks::class)

above my test class declaration I started to get this Looper not mocked error again. I used this rule before with MockitoJUnitRunner and everything was fine.

Michał Powłoka
  • 1,424
  • 1
  • 13
  • 31
  • Something like this: https://stackoverflow.com/questions/43356314/android-rxjava-2-junit-test-getmainlooper-in-android-os-looper-not-mocked-runt – Faysal Ahmed Aug 17 '18 at 09:09

2 Answers2

13

A bit late for the answer, but just faced the same issue and solved it!

To use PowerMock and InstantTaskExecutorRule you need to add the following annotation:

@RunWith(PowerMockRunner::class)
@PowerMockRunnerDelegate(MockitoJUnitRunner::class) //this line allows you to use the powermock runner and mockito runner
@PrepareForTest(UnderTestClass::class)
class UnderTestClassTest {

    @get:Rule
    var instantExecutorRule = InstantTaskExecutorRule()
Rainmaker
  • 10,294
  • 9
  • 54
  • 89
1

No need to fret as it turns out you can still use this method to test your LiveData observers!

First, add this dependency in your module’s build.gradle file:

testImplementation 'android.arch.core:core-testing:1.0.0-alpha3'

Make sure you use the same version as the rest of your android.arch.* dependencies!

Then, in the test class where you need to call setValue() and assert, add this field:

@Rule
public TestRule rule = new InstantTaskExecutorRule();

For Kotlin

@get:Rule
var rule: TestRule = InstantTaskExecutorRule()

Behind the scenes, this bypasses the main thread check, and immediately runs any tasks on your test thread, allowing for immediate and predictable calls and therefore assertions.

Already have this answer here.

Faysal Ahmed
  • 7,501
  • 5
  • 28
  • 50
  • 2
    I already use this Rule. The problem is since I use PowerMockRunner this Rule has no effect. I started to get this exception again, as if I would not use this rule at all. It worked fine as long as I used regular MockitoJUnitRunner, but in this test I need to use that one. – Michał Powłoka Aug 17 '18 at 09:20