Accessing instrumentation test resources

Vasanth Asokan picture Vasanth Asokan · Mar 7, 2011 · Viewed 9.2k times · Source

I am trying to find a way for my instrumentation tests to have access to string resources generated within the test package.

More details:

I have an Android test case which inherits from ActivityInstrumentationTestCase2. I used Eclipse's New Android Test Project to create the test in the first place. The test project has resources (similar to the resources for a regular Android project). I am trying to find a way to programmatically access String resources in the test project in the various individual tests. I have tried:

String s = getInstrumentation().getContext().getString(R.string.blah);

and

String s = mActivity.getApplicationContext().getString(R.string.blah);

Both methods throw a NotFoundException. I have the string "blah" defined in my strings.xml. R in code above is an import from my test package and not the package of the application under test. I am able to access resources defined in the application package with the latter call.

It would be useful to figure out a way to access XML defined string resources in my tests (as I want to avoid typing strings into code). What am I doing wrong?

Answer

cody picture cody · Aug 4, 2011

Even if this post is no longer current - this addition might help someone:

To understand how this works, you have to keep in mind that the context your instrumentation lives in is another than the context of the application you're running your test against. As you stated correctly, you CAN'T access the resources of your target from the instumentation context. You can define some for your instrumentation context in a separate xml-file inside the test project, or - if you want to make use of the predefined resources - you can get them this way:

 Resources res = getInstrumentation().getTargetContext().getResources();
 res.getString(R.string.xxx); // get a string resource

Neither the instrumentation context (as Wujun wrote), nor the target context is available, until the testcase construction has fully completed.