问题
What might be the problem? My Robolectric tests ran fine a while ago, but now they all fail with the same error. The only change I can think of is changing to version 2.1.1. I'm running them with the RobolectricTestRunner and the run configuration points to the actual app directory.
But every test fails because the app's application class is always null as preferences are being accessed:
java.lang.NullPointerException: can't get a shadow for null
at org.robolectric.bytecode.ShadowWrangler.shadowOf(ShadowWrangler.java:414)
at org.robolectric.Robolectric.shadowOf_(Robolectric.java:1077)
at org.robolectric.Robolectric.shadowOf(Robolectric.java:483)
at org.robolectric.shadows.ShadowPreferenceManager.getDefaultSharedPreferences(ShadowPreferenceManager.java:21)
at android.preference.PreferenceManager.getDefaultSharedPreferences(PreferenceManager.java)
at com.foo.bar.FooApplication.onCreate(FooApplication.java:90)
回答1:
Apparently the error occurred because of this in the onCreate of my application class:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
Changed the getBaseContext() to this and the tests work again.
来源:https://stackoverflow.com/questions/17028933/robolectric-tests-fail-on-shadowof