Robolectric tests fail on shadowOf

不羁岁月 提交于 2019-12-14 03:12:49

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!