getSystemService in Robolectric returns object with null Context

自古美人都是妖i 提交于 2019-11-30 22:57:51
Alex Florescu

I played around with this a bit and I actually think that at the moment the answer for this is no, there is no way.

Now, if the purpose is to just avoid the NPE when creating the activity, you might be able to get away with Mocking the AudioManager by doing something like this in your test, for Robolectric versions < 3:

    AudioManager mockManager= Mockito.mock(AudioManager.class);
    Application application = (Application) Robolectric.getShadowApplication().getApplicationContext();
    ShadowContextImpl shadowContext = (ShadowContextImpl) Robolectric.shadowOf(application.getBaseContext());
    shadowContext.setSystemService(Context.AUDIO_SERVICE, mockManager);

Another variant might be to create your own ShadowAudioManager that either handles registerMediaButtonEventReceiver or initialises with the correct context, because the current one does not do that, but I haven't actually tried that.

In order to avoid a similar NPE crash I added the

 @Config(emulateSdk = 18, shadows = {ShadowAudioManager.class}) 

in the class that contains the test!

With Robolectric 3+ use:

AudioManager mockManager= Mockito.mock(AudioManager.class);
Application application = (Application) Robolectric.getShadowApplication().getApplicationContext();
ShadowContextImpl shadowContext = (ShadowContextImpl) Shadows.shadowOf(application.getBaseContext());
shadowContext.setSystemService(Context.AUDIO_SERVICE, mockManager);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!