在我的案例中读取Android测试项目中的文件
我有一个Android测试项目,项目结构如下:在我的案例中读取Android测试项目中的文件,android,android-testing,Android,Android Testing,我有一个Android测试项目,项目结构如下: MyAndroidTestProj - src/ - MyTestCase.java - res/ - raw/ - file1 public class MyTestCase extends AndroidTestCase { @Override public void setUp() throws Exception { super.setUp(); //Ho
MyAndroidTestProj
- src/
- MyTestCase.java
- res/
- raw/
- file1
public class MyTestCase extends AndroidTestCase {
@Override
public void setUp() throws Exception {
super.setUp();
//How to read the file1 under res/raw/ folder?
}
...
}
MyTestCase是这样的:
MyAndroidTestProj
- src/
- MyTestCase.java
- res/
- raw/
- file1
public class MyTestCase extends AndroidTestCase {
@Override
public void setUp() throws Exception {
super.setUp();
//How to read the file1 under res/raw/ folder?
}
...
}
我想知道如何阅读
res/raw/
下的file1
?是否有特定于Android的读取文件的方法?您应该首先获取资源的id,然后将其转换为InputStream,例如使用其内容。因此,请使用以下代码:
InputStream ins = getResources()
.openRawResource(getResources()
.getIdentifier("raw/FILENAME_WITHOUT_THE_EXTENSION","raw", getPackageName()));
然后使用一个BufferedReader
可以获得InputStream
BufferedReader r = new BufferedReader(new InputStreamReader(ins));
StringBuilder content = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
content.append(line);
}
编辑: 如前所述,AndroidTestCase不提供
getInstrumentation
,但它提供了一个getContext()
方法,该方法为您提供了测试应用程序的上下文。但是,当您想要从测试应用程序中获取资源时,您需要访问getTestContext()
方法,该方法在AndroidTestCase中定义,但是是隐藏的
作为一种解决方法,您可以使用反射来访问它,如下所述:
旧答案:
要从测试项目内部获取原始资源,请使用
getInstrumentation().getContext().getResources().openRawResource(R.raw.file1);
如果要从测试项目中获取它们,则必须使用目标上下文:
getInstrumentation().getTargetContext().getResources().openRawResource(R.raw.file1);
我的测试用例扩展了
AndroidTestCase
,它没有getInstrumentation()
方法。我编辑了我的答案以解决AndroidTestCase问题。