Gen*_*Sys 6 android unit-testing
我正在使用InstrumentationTestCase单元测试我的应用程序的一个组件.
该组件将数据持久保存到内部存储,并用于Context::fileList();检索持久文件.
我遇到以下问题:在应用程序中使用此方法(在设备上)工作完全正常.但是,当我尝试(Android-)单元测试(也在设备上)使用InstrumentationTestCase我得到一个NullPointerException内部的fileList()方法.我深入研究android源代码并发现getFilesDir() (参见此处的源代码)返回null并导致此错误.
要重现的代码如下:
public class MyTestCase extends InstrumentationTestCase
{
public void testExample() throws Exception
{
assertNotNull(getInstrumentation().getContext().getFilesDir()); // Fails
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题是:这种行为是否有意?我该怎么做才能绕过这个问题?我使用InstrumentationTestCase正确还是应该使用不同的东西?
Mic*_*hal 10
我认为您将测试数据与测试应用程序分开是正确的.
您可以通过执行以下命令为app Null创建files目录来解决问题Instrumentation
adb shell
cd /data/data/<package_id_of_instrumentation_app>
mkdir files
Run Code Online (Sandbox Code Playgroud)
您只能在模拟器或root设备上执行此操作.
然后从你的问题测试不会失败.我做到了,还上载的文件命名tst.txt到files目录,所有下面的测试是成功的:
assertNotNull(getInstrumentation().getContext().getFilesDir());
assertNotNull(getInstrumentation().getContext().openFileInput("tst.txt"));
assertNotNull(getInstrumentation().getContext().openFileOutput("out.txt", Context.MODE_PRIVATE));
Run Code Online (Sandbox Code Playgroud)
但我认为为测试项目提供数据的更方便的方法是使用assets测试项目,您可以在其中简单地保存一些文件并打开它们:
assertNotNull(getInstrumentation().getContext().getAssets().open("asset.txt"));
Run Code Online (Sandbox Code Playgroud)
或者如果您想将一些测试结果保存到文件中,您可以使用ExternalStorage:
File extStorage = Environment.getExternalStorageDirectory();
assertNotNull(extStorage);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2806 次 |
| 最近记录: |