GetSystemService in Robolectric returns object with null context

In my activity onCreate

, I have:

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

      

When testing activity with Robolectric, I create it with

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

      

Then it is created AudioManager

, but with mContext = null

, which results in NullPointerException

when called registerMediaButtonEventReceiver

on it, because this struct method uses the context internally.

Is there a way to make sure it's AudioManager

set up with a worker Context

?

+3


source to share


3 answers


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

Now, if the goal is simply to avoid NPE when creating this action, you can get away with Mocking the AudioManager by doing something like this in your test, for Robolectric <3 versions:



    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 option could be to create a custom ShadowAudioManager that either handles registerMediaButtonEventReceiver

or initializes the correct context, because the current one doesn't, but I haven't really tried that.

+3


source


Using Robolectric 3+:



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

      

+3


source


To avoid a similar NPE crash, I added

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

      

in the class that contains the test!

+2


source







All Articles