How can I get context of test application itself in ApplicationTestCase<MyApp>?
How can I get context of test application itself in ApplicationTestCase<MyApp>
?
I use test application's resources to store some reference data, but I cannot acquire it's context, as far as I see.
I'm trying to do the following:
referenceContents = readRawTextFile(
getSystemContext(),
//test application's res namespace is myApp.test.*开发者_C百科
myApp.test.R.raw.reference_file);
where readRawTextFile
is simple text reader routine, but the data I get is wrong.
If you need the context of the application you're testing (i.e. MyApp) then this is how you do it:
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);
}
}
As you can see, you get the context of your application under test using:
getContext()
in your test case.
However if you have two separate projects: One is your application and one is your test project and you need the context of the testproject, then the only choice you have is to extend InstrumentationTestCase instead of ApplicationTestCase - however, this means that you won't be able to obtain a context of the application project, but only a context of your test project.
精彩评论