Robolectric TypedArray getString() returns null or

2019-07-31 10:31发布

问题:

I'm using Robolectric to test an activity that inflates a custom view, but when fetching values from the TypedArray everything comes back null or an empty string. What needs to be done in order to get the correct value from the typed array?

回答1:

Robolectric doesn't re-implement the entire Android standard library.

Here is a link to the TypeArray Shadow class: https://github.com/pivotal/robolectric/blob/master/src/main/java/com/xtremelabs/robolectric/shadows/ShadowTypedArray.java

It seems to be missing some things. You can use this function to confirm that it is indeed missing those functions: http://pivotal.github.com/robolectric/javadoc/com/xtremelabs/robolectric/Robolectric.html#logMissingInvokedShadowMethods()

That said, there is hope. Robolectric 2.0 Alpha 1 was recently released. While I haven't used it yet, it claims that less shadow implementations will be needed as it will use the Android implementations directly.



回答2:

Try using getStringArray() instead. For example:

String[] myStringArray = Robolectric.getShadowApplication().getResources()
    .getStringArray(R.array.MyStringArrayIdentifier)