Robolectric中的getSystemService返回具有空上下文的对象

ric*_*fox 4 android robolectric

在我的活动中,onCreate我有:

AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
Run Code Online (Sandbox Code Playgroud)

使用Robolectric测试活动时,我使用

ActivityController<MainActivity> controller = Robolectric.buildActivity(MainActivity.class);
MainActivity activity = controller.attach().create().get();
Run Code Online (Sandbox Code Playgroud)

AudioManager随后创建,但与mContext = null这导致了NullPointerException时调用registerMediaButtonEventReceiver它,因为该框架方法使用上下文内部。

有什么方法可以确保AudioManager使用工作方式创建Context

Ale*_*scu 6

我对此进行了一些尝试,实际上我认为目前此答案是否定的,没有办法。

现在,如果目的是在创建活动时避免使用NPE,那么对于测试版本<3的Robolectric,您可以通过在测试中执行类似的操作来嘲笑AudioManager。

    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);
Run Code Online (Sandbox Code Playgroud)

另一个变体可能是创建您自己的ShadowAudioManager,以registerMediaButtonEventReceiver正确的上下文来处理或初始化它,因为当前的那个并没有这样做,但是我实际上没有尝试过。