【问题标题】:Assets folder in Android Studio Unit TestAndroid Studio 单元测试中的资产文件夹
【发布时间】:2014-07-06 22:52:23
【问题描述】:

我有一个 Gradle 项目,其结构如下:

project/
    src/
        androidTest/
            java/
        main/
            java/
            res/
            AndroidManifest.xml
    build.gradle

现在我想添加一个使用资源(“原始”或“资产”)的单元测试。

我将我的资源放入project/androidTest/assets/test_file 并使用getContext().getResources().getAssets().open("test_file"); 访问它(在AndroidTestCase 中)。

但是,这给了我一个FileNotFoundException。我该如何解决这个问题?

【问题讨论】:

  • 好的,我现在把它作为原始资源工作(确保导入yourpackage.test.R,而不是yourpackage.R)。
  • 你能详细解释一下吗?我对此很困扰。我需要单独的资产进行测试。我应该如何在 gradle 或任何可能的方式中进行配置?

标签: java android unit-testing android-resources


【解决方案1】:

您似乎正在尝试创建一个检测单元测试,因为您想在 androidTest 文件夹中创建它。

您可以在测试中使用以下两行之一来获取上下文:

  • Context ctx = InstrumentationRegistry.getTargetContext(); 这将为您提供应用程序的上下文。例如,您可以使用它来抓取 src/ma​​in/assets 中的资产。

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

    中的资产

如果您想了解更多关于单元测试资产的信息,可以阅读this 帖子。在this github file 你有一个例子。

弃用说明:正如 cmets 中所指出的,这些方法现在已弃用。这是新的推荐方式:

  • 首先,不要导入the old InstrumentationRegistry 类,而是使用the new one
  • 使用ApplicationProvider.getApplicationContext() 代替InstrumentationRegistry.getTargetContext();Source
  • 对于InstrumentationRegistry.getTargetContext();:在大多数情况下,应使用ApplicationProvider.getApplicationContext() 而不是仪器测试上下文。如果您确实需要访问测试上下文以访问其资源,建议改用PackageManager.getResourcesForApplication(String)Source

【讨论】:

  • 两者都是@Deprecated
【解决方案2】:

我认为您使用了错误的上下文(应用程序上下文而不是检测上下文)使用:

getInstrumentation().getContext();

或者在这里查看我在哪里做你想做的事:https://github.com/ligi/gobandroid/blob/master/android/src/androidTest/java/org/ligi/gobandroidhd/base/AssetAwareInstrumentationTestCase.java

【讨论】:

  • 链接坏了,很遗憾。
猜你喜欢
  • 2013-10-14
  • 2015-09-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-29
  • 1970-01-01
  • 1970-01-01
  • 2014-05-09
相关资源
最近更新 更多