国内 Robolectric 相关的文档是在太少了,特写此篇,加深记忆
代码层面小优化
基类
@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 26)
public abstract class BaseRobolectric {
@Before
public void setUp() {
ShadowLog.stream = System.out;
}
public Application getApplication() {
return RuntimeEnvironment.application;
}
public Context getContext() {
return RuntimeEnvironment.application;
}
}
常见的问题
常用方法:多 clean 几次,清理缓存文件
- java.io.FileNotFoundException: build\intermediates\bundles\debug\AndroidManifest.xml (系统找不到指定的路径。)
解决方案:
方案一:
1.编辑运行配置 Defaults → Android JUnit
2.Working directory的值修改为 M O D U L E D I R MODULE_DIR MODULEDIR
方案二:
自定义 RobolectricTestRunner ,把路径写死,如下:
public class MyRoboRunner extends RobolectricTestRunner {
/**
* Creates a runner to run {@code testClass}. Looks in your working directory for your AndroidManifest.xml file
* and res directory by default. Use the {@link Config} annotation to configure.
*
* @param testClass the test class to be run
* @throws InitializationError if junit says so
*/
public MyRoboRunner(Class<?> testClass) throws InitializationError {
super(testClass);
}
@Override
protected AndroidManifest getAppManifest(Config config) {
// return super.getAppManifest(config);
String appRoot = "../";
String resDir = appRoot + "build/intermediates/res/merged/debug/";
String assetDirt = appRoot + "build/intermediates/assets/debug/";
return new AndroidManifest(Fs.fileFromPath("../src/main/AndroidManifest.xml"),
Fs.fileFromPath(resDir),Fs.fileFromPath(assetDirt)){
@Override
public List<ResourcePath> getIncludedResourcePaths() {
List<ResourcePath> paths = super.getIncludedResourcePaths();
return paths;
}
};
}
}
方案三:
请在尝试过方案一和方案二都无效后,再尝试方案三
@Config 中 manifest 设置为 Config.NONE
- Application未初始化
解决方案:
@Config 中 application 设置为自定义的 application
关注我的技术公众号,每个工作日都有优质技术文章推送。
微信扫一扫下方二维码即可关注: