微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Android InstrumentationTestCase getFilesDir()返回null

我正在使用InstrumentationTestCase对我的应用程序的一个组件进行单元测试.

该组件将数据持久保存到内部存储并使用Context :: fileList();检索持久化文件.

我遇到以下问题:在应用程序中使用此方法(在设备上)工作完全正常.但是当我尝试使用InstrumentationTestCase(Android-)单元测试(也在设备上)时,我在fileList()方法中得到一个NullPointerException.我深入研究android源代码,发现getFilesDir()(see source here)返回null并导致此错误.

要重现的代码如下:

public class MyTestCase extends InstrumentationTestCase
{   
    public void testExample() throws Exception
    {
        assertNotNull(getInstrumentation().getContext().getFilesDir()); // Fails
    }
}

我的问题是:这种行为是否有意?我该怎么做才能绕过这个问题?我是使用InstrumentationTestCase还是应该使用不同的东西?

我找到了this question,但我不确定这是否涵盖了我遇到的同样问题.

解决方法

我认为您将测试数据与测试应用程序分开是正确的.

您可以通过执行以下命令为Instrumentation app创建文件目录来解决Null问题

adb shell
cd /data/data/<package_id_of_instrumentation_app>
mkdir files

您只能在模拟器或root设备上执行此操作.

然后从你的问题测试不会失败.我做了它并且还将名为tst.txt的文件上传文件dir,所有以下测试都成功:

assertNotNull(getInstrumentation().getContext().getFilesDir());
assertNotNull(getInstrumentation().getContext().openFileInput("tst.txt"));
assertNotNull(getInstrumentation().getContext().openFileOutput("out.txt",Context.MODE_PRIVATE));

但我认为为测试项目提供数据的更方便的方法是使用测试项目的资产,您可以在其中简单地保存一些文件并打开它们:

assertNotNull(getInstrumentation().getContext().getAssets().open("asset.txt"));

或者如果要将某些测试结果保存到文件中,可以使用ExternalStorage:

File extStorage = Environment.getExternalStorageDirectory();
assertNotNull(extStorage);

原文地址:https://www.jb51.cc/android/310740.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐