[英]Robolectric Resources$NotFoundException with getBoolean() and getInteger()
I have set up robolectric unit tests for my app and encountered a Problem with integer and boolean resources defined in XML. 我已经为我的应用程序设置了robolectric单元测试,并且遇到了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. Robolectric似乎可以正确找到一些资源,因为getString(...)
和getDrawable(...)
可以正常工作。 However, getBoolean(...)
and getInteger(...)
fail with a Resources$NotFoundException
. 但是, getBoolean(...)
和getInteger(...)
失败,出现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? 这是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. 更新似乎与我的res
文件夹有关。 I started from a fresh Android project, and the single test above. 我从一个新的Android项目开始,然后是上面的单个测试。 I then added my project dependencies: the test still ran. 然后,我添加了项目依赖项:测试仍然运行。 I copied my res
folder to the new project: the test failed. 我将res
文件夹复制到了新项目:测试失败。
I found the error. 我发现了错误。 It turns out that Robolectric does not support the item tag for resources declared in XML. 事实证明,Robolectric 不支持 XML声明的资源的item标记 。 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. 但是,Robolectric XML解析器在解析布尔值时仅检查bool
节点,而不检查item
节点。 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. 现在,Robolectric可以正确解析资源。 Note that both ways seem to be equally valid in the normal Android runtime. 请注意,这两种方法在正常的Android运行时中似乎同样有效。 I didn't check the official docs if there is any recommendation though. 我没有检查官方文档,尽管有任何建议。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.