简体   繁体   English

使用Robolectric进行测试时,Android WorkManager出错

[英]Android WorkManager has error when testing with Robolectric

I'm using Android work manager with a custom initialization. 我正在使用Android工作管理器进行自定义初始化。 to do that i disable auto-initialization in the manifest like this 要做到这一点,我在清单中禁用这样的自动初始化

        <provider
        tools:replace="android:authorities"
        android:name="androidx.work.impl.WorkManagerInitializer"
        android:authorities="${applicationId}.work_manager_init"
        android:enabled="false"
        android:exported="false" />

And in application code I use this code 在应用程序代码中我使用此代码

private fun initWorkManager() {
    WorkManager.initialize(this, Configuration.Builder().run {
        setWorkerFactory(appComponent.daggerWorkerFactory())
        build()
    })
}

And it works fine when I run my application. 当我运行我的应用程序时,它工作正常。 But when I'm testing with roboletric any class that needs the context by RuntimeEnvironment.application throws this exception 但是当我使用roboletric测试任何需要RuntimeEnvironment.application上下文的RuntimeEnvironment.application会抛出此异常

java.lang.IllegalStateException: WorkManager is already initialized.  
Did you try to initialize it manually without disabling 
WorkManagerInitializer? See WorkManager#initialize(Context, 
Configuration) or the class levelJavadoc for more information.

The initWorkManager() get calls and throw this beacuse it doesn't know auto-init is already disabled in the manifest and somehow my test cannot read the values from the manifest file. initWorkManager()得到调用并抛出这个因为它不知道自动初始化已经在清单中被禁用,并且某种程度上我的测试无法读取清单文件中的值。

Any help or suggestion will be appritiated. 任何帮助或建议都将被批准。

I solved a similar issue with the help of the Androidx Work Manager testing utils. 我在Androidx Work Manager测试工具的帮助下解决了类似的问题。 For reference see the docs here: Android work manager testing docs 有关参考,请参阅此处的文档: Android工作管理器测试文档

Basically what you need to do is add a dependency to include the work manger test utils: 基本上你需要做的是添加一个依赖项来包含工作管理器测试工具:

testImplementation 'androidx.work:work-testing:2.0.1'

Then you will be able to call code in your test setup similar to this: 然后,您将能够在测试设置中调用与此类似的代码:

final Configuration config = new Configuration.Builder()
    .setMinimumLoggingLevel(Log.DEBUG)
    .setExecutor(new SynchronousExecutor())
    .build();
WorkManagerTestInitHelper.initializeTestWorkManager(
    context, config);

Whereas the context could obtained in different ways, depending on your test infrastructure. 鉴于上下文可以通过不同方式获得,具体取决于您的测试基础架构。

With this approach no other steps like excluding something from the manifest are necessary. 使用这种方法,不需要从清单中排除某些东西等其他步骤。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM