Robolectric官网上给了一个配置教程,但是我使用它的方法进行配置,发现使用Mockito.spy函数的时候会出现Exception。
后来在PowerMock官网上找到了另外一个教程,里面说使用PowerMockRule是不靠谱的,要使用PowerMock 1.6.0引入的新的@PowerMockRunnerDelegate annotation来进行配置
具体配置文件如下:
module里面的build.gradle添加依赖:
dependencies {
......
testCompile "org.robolectric:robolectric:3.0"
testCompile ‘org.mockito:mockito-core:1.10.19‘
testCompile ‘junit:junit:4.12‘
testCompile "org.powermock:powermock-module-junit4:1.6.4"
testCompile "org.powermock:powermock-module-junit4-rule:1.6.4"
testCompile "org.powermock:powermock-api-mockito:1.6.4"
testCompile "org.powermock:powermock-classloading-xstream:1.6.4"
}
对下面的 RobolectricTest 基类进行继承,就可以正常使用PowerMock和Robolectric进行测试了
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.modules.junit4.PowerMockRunnerDelegate;
import org.robolectric.RobolectricGradleTestRunner;
import org.robolectric.annotation.Config;
/**
* Base class extended by every Robolectric test in this project.
*/
@RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate(RobolectricGradleTestRunner.class)
@Config(constants = BuildConfig.class,
sdk = 21)
@PowerMockIgnore({"org.mockito.*", "org.robolectric.*", "android.*"})
public abstract class RobolectricTest {
}
时间: 2024-11-04 09:14:49