安卓测试原始资源

43

我在Android Studio中有以下文件夹结构:

├── androidTest
│   ├── java
│   └── res
│       └── raw
│           └── test_file
└── main
    ├── java
    └── res
        └── raw
            └── app_file

我正试图访问位于androidTest元素的raw文件夹中存在的test_file资源。以下是继承自ActivityInstrumentationTestCase2的Robotium测试用例中的代码:

InputStream is = this.getInstrumentation()
                 .getContext()
                 .getResources()
                 .openRawResource(R.raw.test_file);

Android Studio 抛出引用错误,因为找不到资源。确切的错误是“Cannot resolve symbol test_file”。

我要如何从 androidTest 资源包中的测试用例引用此资源?


你有没有一个可以为你生成树形结构的工具? - Archimedes Trajano
是的,Bash中的'tree'工具。 - jlhonora
很好,谢谢你的提示。 - Archimedes Trajano
1
你是从哪里获取你的 test_file 的?是从 androidTest/java 中编写的 Robotium 测试中吗? - pdegand59
4个回答

54

默认情况下,您的androidTest项目将包括应用程序的R类,但是androidTest的资源将生成到单独的文件中。请确保从测试项目导入R类:

import com.your.package.test.R;

[..]

getInstrumentation().getContext().getResources().openRawResource(R.raw.test_file);

您还可以直接引用测试项目的R类:

getInstrumentation().getContext().getResources().openRawResource(com.your.package.test.R.raw.test_file);

8
我有和原帖相同的文件结构,但在androidTest变体中没有生成raw文件夹。 - Yaroslav Mytkalyk
@YaroslavMytkalyk,您要将什么类型的文件放入原始文件夹中? - jlhonora
@jlhonora 一个没有扩展名的二进制文件。尝试重命名并添加一些任意扩展名,但这并没有改变什么。 - Yaroslav Mytkalyk
通过这样做,资源也会出现在发布的APK中。如何避免这种情况? - Victor Paléologue

18

我将androidTest资源放在正确的位置(src/androidTest/res),但我仍然无法通过<normal.package>.test.R访问它们。我花了很多时间在谷歌上搜索,试图弄清楚发生了什么......

最终我偶然找到了答案。如果你正在构建一个指定了applicationIdSuffixbuildType,那么你的文件位于<applicationId><applicationIdSuffix>.test.R!!!!

即:

applicationId "com.example.my.app"

buildTypes {
    debug {
        applicationIdSuffix ".debug"
    }
}

如果您在正确的目录中拥有androidTest资源,则只能通过com.example.my.app.debug.test.R访问它们 !!!!


即使没有使用applicationIdSuffix,如果applicationId与您的包名称不同,您仍应该使用<applicationId>.test.R - yshahak

1
正如其他人所说,androidTest资源ID默认情况下是在<applicationId>.test.R中生成的。由于applicationId可以被不同的构建类型和风味修改,这导致每个构建类型/风味都有不同的R文件位置。可以通过在build.gradle中为应用程序android配置的defaultConfig分配显式值来更改这种情况中的testApplicationId。如果有多个构建类型/风味会改变appId,但测试可以运行任何一个,则可能会很有用。
android {
    defaultConfig {
    applicationId "com.example.hello"
    testApplicationId = "com.example.hello.test"
    }
}

测试文件:

import com.example.hello.test.R

1
请查看需要Context的Android单元测试。对于仪器化测试,请使用InstrumentationRegistry.getInstrumentation().getTargetContext()(在Kotlin中:getInstrumentation().targetContext)。然后您可以访问resources。您不需要导入R文件。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接