Robolectric 单元测试仅在 运行 宁多模块单元测试 运行 配置时使用旧版而不是二进制资源

Robolectric unit tests using legacy instead of binary resources only when running multi-module unit test run config

我有一个多模块 android 项目。我在每个模块中都有一堆单元测试,我总是能够使用像这样的 运行 配置一次 运行 它们:

我的许多测试都使用 class 基础 运行 与 RobolectricTestRunner。这个基地 class 看起来像这样:

@RunWith(RobolectricTestRunner::class)
@Config(application = AndroidTest.ApplicationStub::class,
        manifest = Config.NONE,
        sdk = [21])
abstract class AndroidTest {
    @Suppress("LeakingThis")
    @Rule @JvmField val injectMocks = InjectMocksRule.create(this@AndroidTest)

    fun application(): Application = ApplicationProvider.getApplicationContext()

    internal class ApplicationStub : Application()
}

**当运行使用上述配置进行这些测试时,出现错误**

[Robolectric] NOTICE: legacy resources mode is deprecated; see http://robolectric.org/migrating/#migrating-to-40

这使我的许多测试因 ResourceNotFoundException

而失败

但是,当我 运行 仅在特定模块中进行测试时,一切都通过了。这是因为 Robolectric 现在使用二进制资源:

[Robolectric] sdk=21; resources=BINARY

我已按照每个模块的 build.gradle 文件中的迁移说明进行操作,并在每个 android 块中添加了以下内容:

testOptions {
    unitTests {
        includeAndroidResources = true
        returnDefaultValues = true
    }
}

我发现但无法解决的一个线索是当我 运行 ALL UNIT TEST 任务时:

WARNING: No manifest file found at build/intermediates/merged_manifests/debug/../../library_manifest/debug/AndroidManifest.xml.
Falling back to the Android OS resources only.
No such manifest file: build/intermediates/merged_manifests/debug/../../library_manifest/debug/AndroidManifest.xml
To remove this warning, annotate your test class with @Config(manifest=Config.NONE).

如您所见,我已尝试添加清单=Config.NONE,但没有效果(现在已弃用)。

编辑:还在 settings.gradle 中尝试了 android.enableUnitTestBinaryResources = true,但这会阻止应用程序构建,因为它是当前 gradle 工具中的弃用标志。

感谢您提供的任何帮助!

因此,在 Android Studio 中将默认单元测试 运行 平台更改为 Gradle 后,我设法找到了一种在多个单元中进行 运行 单元测试的方法一次全部模块,绕过 Robolectric 错误。

首先,进入 运行 配置并创建一个新的 Gradle 配置。

然后,作为gradle项目,select顶级项目。 对于参数,使用 --tests "*"

现在对于 gradle 任务,这更容易出错。这是我如何为我的项目设置它的示例:

:androidrma:cleanTestGoogleDebugUnitTest :androidrma:testGoogleDebugUnitTest 
:calendar:cleanTestDebugUnitTest :calendar:testDebugUnitTest 
:gamification:cleanTest :gamification:test 
:player:cleanTest :player:test 
:playlists:cleanTest :playlists:test 
:sleepjournal:cleanTest :sleepjournal:test 
:sound-content-filters:cleanTest :sound-content-filters:test

请注意,为了更清晰,我在每个模块之间插入了新行,在任务中,只需用 space.

分隔每个条目

对于您的应用程序模块,在我的例子中名为 androidrma,您必须在 cleanTestUnitTest 和 testUnitTest 中使用您的构建变体名称,在我的例子中是 GoogleDebug。

如果我们看一下日历模块,它是一个 android 模块,所以它仍然以与 appModule 相同的逻辑运行。

但是,如果您查看播放器、播放列表、sleepjournal 等,这些都是纯kotlin 模块。因此,这些任务的语法不同。

一旦您输入了所有这些信息并且一切正常,我建议选中 运行 配置设置屏幕右上角的“存储为项目文件”复选框。

这适用于 Android Studio 4.2 以及 Arctic Fox,尚未在其他版本上测试。