Search code examples
androidkotlinpowermockitoandroid-livedata

Testing LiveData using PowerMockRunner


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.


Solution

  • 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()