Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getSystemService in Robolectric returns object with null Context

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?

like image 863
rickythefox Avatar asked Sep 24 '14 15:09

rickythefox


2 Answers

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.

like image 104
Alex Florescu Avatar answered Oct 19 '22 21:10

Alex Florescu


In order to avoid a similar NPE crash I added the

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

in the class that contains the test!

like image 38
madlymad Avatar answered Oct 19 '22 21:10

madlymad