Robolectric升级篇

国内 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

关注我的技术公众号,每个工作日都有优质技术文章推送。
微信扫一扫下方二维码即可关注:
图片

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值