我有一个 Gradle 项目,其结构如下:
project/
src/
androidTest/
java/
main/
java/
res/
AndroidManifest.xml
build.gradle
现在我想添加一个使用资源(“原始”或“ Assets ”)的单元测试。
我将我的资源放入 project/androidTest/assets/test_file
并使用 getContext().getResources().getAssets().open("test_file");
访问它code>(在 AndroidTestCase
中)。
但是,这给了我一个 FileNotFoundException
。我该如何解决这个问题?
最佳答案
您似乎正在尝试创建一个检测单元测试,因为您想在 androidTest 文件夹中创建它。
您可以在测试中使用以下两行之一来获取上下文:
Context ctx = InstrumentationRegistry.getTargetContext();
这将为您提供应用程序的上下文。例如,您可以使用它来获取 src/main/assets 中的 Assets 。
中的 AssetsContext ctx = InstrumentationRegistry.getContext();
这将为您提供测试应用程序的上下文。您可以使用它来抓取 src/androidTest/assets
如果您想了解更多关于单元测试 Assets 的信息,您可以阅读 this邮政。在 this github file你有一个例子。
弃用说明:正如评论中所指出的,这些方法现已弃用。这是新的推荐方式:
- 首先,而不是导入 the old
InstrumentationRegistry
类,使用 the new one . - 使用
ApplicationProvider.getApplicationContext()
代替InstrumentationRegistry.getTargetContext();
。 Source - 对于
InstrumentationRegistry.getTargetContext();
:在大多数情况下,应该使用ApplicationProvider.getApplicationContext()
代替instrumentation测试上下文。如果您确实需要访问测试上下文以访问其资源,建议使用PackageManager.getResourcesForApplication(String)
代替。 Source
关于java - Android Studio 单元测试中的 Assets 文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24601053/