getSystemService in Robolectric returns object with null Context

ぃ、小莉子 提交于 2019-12-19 03:31:14

问题


In my activity's onCreate I have:

AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

When testing the activity with Robolectric I create it with

ActivityController<MainActivity> controller = Robolectric.buildActivity(MainActivity.class);
MainActivity activity = controller.attach().create().get();

The AudioManager is then created but with mContext = null which leads to a NullPointerException when calling registerMediaButtonEventReceiver on it because that framework method uses the context internally.

Is there any way to make sure the AudioManager is created with a working Context?


回答1:


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.




回答2:


In order to avoid a similar NPE crash I added the

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

in the class that contains the test!




回答3:


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);


来源:https://stackoverflow.com/questions/26021305/getsystemservice-in-robolectric-returns-object-with-null-context

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