使用PowerMockRunner测试LiveData

时间:2018-08-17 09:02:13

标签: android kotlin powermockito android-livedata

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

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

因为本地JVM无法访问Android框架。我使用它来解决该问题:

@get:Rule
val rule = InstantTaskExecutorRule()

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

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

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

2 个答案:

答案 0 :(得分:3)

答案来得有点晚,但遇到了同样的问题并解决了!

要使用PowerMockInstantTaskExecutorRule,您需要添加以下注释:

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

答案 1 :(得分:1)

无需烦恼,事实证明您仍然可以使用此方法测试LiveData观察者!

首先,将此依赖性添加到模块的build.gradle文件中:

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

请确保使用与其他android.arch。*依赖项相同的版本!

然后,在需要调用setValue()并进行断言的测试类中,添加以下字段:

@Rule
public TestRule rule = new InstantTaskExecutorRule();

科特林

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

在后台,这绕过了主线程检查,并立即在您的测试线程上运行任何任务,从而允许立即和可预测的调用以及因此的断言。

已经有了这个答案here