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
?
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With