Question

I have set up robolectric unit tests for my app and encountered a Problem with integer and boolean resources defined in XML. I have my tests in a separate project, but set the working directory to the project under test as described in this answer. Robolectric seems to find some of the resources correctly, because getString(...) and getDrawable(...) work fine. However, getBoolean(...) and getInteger(...) fail with a Resources$NotFoundException.

I dumbed down one of the test cases to reproduce the behaviour:

@Test
public void testResources() {

    TestActivity activity = controller.get();
    String theString = activity.getString(R.string.ab_request); // works
    Drawable theDrawable = activity.getResources().getDrawable(R.drawable.ab_back); // works
    boolean theBool = activity.getResources().getBoolean(R.bool.isRelease); // fails
    int theInt = activity.getResources().getInteger(R.integer.act_noNetwork); // fails
}

Is this a known bug with Robolectric? I searched for a while and didn't find anyone with the same problem.

Update It seems it has something to do with my res folder. I started from a fresh Android project, and the single test above. I then added my project dependencies: the test still ran. I copied my res folder to the new project: the test failed.

Was it helpful?

Solution

I found the error. It turns out that Robolectric does not support the item tag for resources declared in XML. My resources were declared as

<item type="bool" name="isRelease">false</item>
<item type="integer" name="act_noNetwork">12345</item>

However, the Robolectric XML parser just checks for bool nodes, and not for item nodes, when parsing booleans. The same goes for integers, I haven't checked other types. I changed my declarations to:

<bool name="isRelease">false</bool>
<integer name="act_noNetwork">12345</integer>

Now Robolectric parses the resources correctly. Note that both ways seem to be equally valid in the normal Android runtime. I didn't check the official docs if there is any recommendation though.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top