java - Android Studio 单元测试中的 Assets 文件夹

标签 java android unit-testing android-resources

我有一个 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/ma​​in/assets 中的 Assets 。

  • Context ctx = InstrumentationRegistry.getContext(); 这将为您提供测试应用程序的上下文。您可以使用它来抓取 src/androidTest/assets

    中的 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/

相关文章:

java - FindBugs :"may fail to close stream ",如何解决?

android - 媒体查询不适用于 Android

java - 为什么通过 Android 向 ASP.NET MVC 站点发送 POST 数据时会出现错误 500?

unit-testing - 应该测试内部实现,还是只测试公共(public)行为?

java - 在Java中,为什么不必调用main方法呢?

java - 从包含任意格式数字的字符串中解析 BigDecimal

java - 字符串的垃圾收集

java - 在 ViewPager 中重新加载 fragment

.net - 如何模拟(使用最小起订量)Unity 方法

unit-testing - 是否有用于单元测试的 cakephp 插件(用于 TDD)?