Jef*_*rod 5 android unit-testing assets copy file
我正在编写一个Android JUnit测试,想要复制/重置测试夹具文件(它是一个SQLite数据库文件.)如果我在主应用程序中,我知道我可以将文件放在assets目录中并使用 getResources().getAssets().open(sourceFile)
但是,此API似乎在ActivityInstrumentationTestCase2课程中不可用.
有没有一种简单的方法可以从测试PC上复制文件,或者我应该在设备上保留一个测试夹具的新副本并将其复制到临时文件中?
谢谢!
测试应用程序和主应用程序中的资源可在仪器测试用例中单独访问.如果要访问测试项目本身的res/raw或assets文件夹中的资源,可以使用
getInstrumentation().getContext().getResources()
Run Code Online (Sandbox Code Playgroud)
要访问正在测试的应用程序中的资源("目标"应用程序),请使用
getInstrumentation().getTargetContext().getResources()
Run Code Online (Sandbox Code Playgroud)
但请注意,您永远不能修改assets文件夹中的文件;
getResources().getAssets().open(sourceFile)
Run Code Online (Sandbox Code Playgroud)
返回一个InputStream.没有办法修改文件.这是因为资产被压缩存储在APK中,并且根本不可写.
如果你想要做的是修改路径的文件你正在测试使用的活动,你应该使用ActivityUnitTestCase和setActivityContext()与RenamingDelegatingContext.这允许您通过指定目录前缀将上下文中的文件和数据库访问重定向到新目录.您甚至可以使用更复杂的构造函数来包装大多数操作的目标上下文,但是使用测试应用程序的上下文进行文件操作,因此活动将访问存储在测试应用程序中的文件而不是主应用程序,但仍然使用其他资源.主要应用.
为了实现这一点,我所做的(以一种不太优雅的方式)是将测试夹具复制到我的设备(或模拟设备)上。我将其命名为“cleantestdatabase.db”。然后在测试代码中,我将其复制到“testdatabase.db”,以便我可以通过测试对其进行修改,但将其重置为已知状态。这是代码:
copyFile("cleantestdatabase.db", "testdatabase.db");
private void copyFile(String source, String dest) throws IOException{
String rootPath = Environment.getExternalStorageDirectory().getAbsolutePath() + getActivity().getString(R.string.default_dir);
File newDir = new File(rootPath);
boolean result = newDir.mkdir();
if(result == false){
Log.e("Error", "result false");
}
InputStream in = new FileInputStream(rootPath + source);
File outFile = new File(rootPath + dest);
if(outFile.exists()) {
outFile.delete();
}
outFile.createNewFile();
OutputStream out = new FileOutputStream(outFile);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1877 次 |
| 最近记录: |