I am trying to find a way for my instrumentation tests to have access to string resources generated within the test package.
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);
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?
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.
String s = getInstrumentation().getContext().getString(com.myProject.test.R.string.blah);
com.myProject is the package of the project to be tested and
com.myProject.test is the package of the testing project.
It worked for me if I place the code inside
setup(). It doesn’t work if I place it inside the constructor.
I think this is not possible without storing the resource files somewhere else, but you can use something like Robotium where you just use Solo.getString() and you get your resource.