Java 如何在ApplicationTestCase中获取测试应用程序本身的上下文<;MyApp>;?
如何在Java 如何在ApplicationTestCase中获取测试应用程序本身的上下文<;MyApp>;?,java,android,testing,Java,Android,Testing,如何在ApplicationTestCase中获取测试应用程序本身的上下文 我使用测试应用程序的资源来存储一些参考数据,但就我所见,我无法获取它的上下文 我正在努力做到以下几点: referenceContents = readRawTextFile( getSystemContext(), //test application's res namespace is myApp.test.* myApp.test.R.raw.reference_file); 其中,r
ApplicationTestCase
中获取测试应用程序本身的上下文
我使用测试应用程序的资源来存储一些参考数据,但就我所见,我无法获取它的上下文
我正在努力做到以下几点:
referenceContents = readRawTextFile(
getSystemContext(),
//test application's res namespace is myApp.test.*
myApp.test.R.raw.reference_file);
其中,
readRawTextFile
是一个简单的文本读取器例程,但我得到的数据是错误的。如果您需要测试的应用程序(即MyApp)的上下文,那么您可以这样做:
public class MyAppTest extends ApplicationTestCase<MyApp> {
public MyAppTest () {
super(MyApp.class);
}
public MyAppTest (Class<MyApp> applicationClass) {
super(applicationClass);
}
@Override
protected void setUp() throws Exception {
super.setUp();
createApplication();
}
public void testMyApp() throws Exception {
// Retrieves a file in the res/xml folder named test.xml
XmlPullParser xml = getContext().getResources().getXml(R.xml.test);
assertNull(xml);
}
}
在您的测试用例中
但是,如果您有两个独立的项目:一个是应用程序,另一个是测试项目,并且您需要测试项目的上下文,那么您唯一的选择是扩展InstrumentationTestCase而不是ApplicationTestCase-但是,这意味着您将无法获得应用程序项目的上下文,但仅限于测试项目的上下文
getContext()