使用PowerMockRunner测试LiveData

Mic*_*oka 1 android kotlin powermockito android-livedata

我的本地单元测试始终使用LiveData。通常,当您尝试在MutableLiveData上设置值时,会得到

java.lang.RuntimeException: Method getMainLooper in android.os.Looper not mocked.
Run Code Online (Sandbox Code Playgroud)

因为本地JVM无法访问Android框架。我使用以下方法修复了该问题:

@get:Rule
val rule = InstantTaskExecutorRule()
Run Code Online (Sandbox Code Playgroud)

一切都很好,直到我不得不使用PowerMockito模拟来自Google Play库的静态方法。自从我添加

@RunWith(PowerMockRunner::class)
@PrepareForTest(Tasks::class)
Run Code Online (Sandbox Code Playgroud)

在我的测试类声明之上,我开始再次得到这个Looper not模拟错误。我之前在MockitoJUnitRunner中使用了此规则,一切都很好。

Rai*_*ker 7

答案有点迟了,但是只是遇到了同样的问题并解决了!

要使用PowerMock并且InstantTaskExecutorRule您需要添加以下注释:

@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()
Run Code Online (Sandbox Code Playgroud)

  • 我不会想出那个。谢谢! (2认同)