问题描述
在我的活动的的onCreate
我有:
AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
在与Robolectric测试活动我创建
When testing the activity with Robolectric I create it with
ActivityController<MainActivity> controller = Robolectric.buildActivity(MainActivity.class);
MainActivity activity = controller.attach().create().get();
的 AudioManager
然后但 mContext = NULL
创建这导致了 NullPointerException异常
调用 registerMediaButtonEventReceiver
上它的时候,因为这一框架方法使用上下文内部。
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.
有没有什么办法,以确保 AudioManager
与工作创建上下文
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.
现在,如果目的是为了只避免创建活动时,NPE,你也许可以通过做这样的事情在您的测试,对于Robolectric版本&LT嘲讽AudioManager脱身; 3:
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);
另一个变种可能是的,要么把手 registerMediaButtonEventReceiver
或正确的上下文初始化,因为当前不这样做,但我并没有真正尝试过。
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.
这篇关于getSystemService在Robolectric收益与空上下文对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!