Android Studio Unit Test中的Assets文件夹 [英] Assets folder in Android Studio Unit Test

查看:723
本文介绍了Android Studio Unit Test中的Assets文件夹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有以下结构的Gradle项目:

I have a Gradle project with the following structure:

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

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

Now I want to add a unit test which uses a resource (either "raw" or "asset").

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

I put my resource into project/androidTest/assets/test_file and access it with getContext().getResources().getAssets().open("test_file"); (in an AndroidTestCase).

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

However, this gives me a FileNotFoundException. How can I fix this?

推荐答案

看起来你正在尝试创建一个检测单元测试,因为你想要创建它位于androidTest文件夹中。

It looks like you're trying to create an instrumented unit test, since you want to create it in the androidTest folder.

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

You can use one of these two lines in your test to get the context:


  • 上下文ctx = InstrumentationRegistry.getTargetContext();
    这个将为您提供应用程序的上下文。您可以使用它来获取src / main / assets中的资产。

  • Context ctx = InstrumentationRegistry.getTargetContext(); this one will give you your app's context. You can use it to grab assets that are in src/main/assets for example.

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

Context ctx = InstrumentationRegistry.getContext(); this one will give you the test app's context. You can use it to grab assets that are in src/androidTest/assets

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

If you want to know more about assets in unit testing you can read this post. In this github file you have an example.

这篇关于Android Studio Unit Test中的Assets文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆