gpt4 book ai didi

Android InstrumentationTestCase getFilesDir() 返回 null

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:40:55 25 4
gpt4 key购买 nike

我正在使用 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 应用程序创建 files 目录来解决 Null 的问题

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

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

然后从你的问题中测试不会失败。我做到了,并将名为 tst.txt 的文件上传到 files 目录,以下所有测试均成功:

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

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

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

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

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

关于Android InstrumentationTestCase getFilesDir() 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14317793/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com