gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:49:34 26 4
gpt4 key购买 nike

在我的 Activity 的 onCreate 中,我有:

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

当使用 Robolectric 测试 Activity 时,我使用它创建它

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

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

有什么方法可以确保 AudioManager 是使用有效的 Context 创建的吗?

最佳答案

我试了一下这个,实际上我认为目前对此的答案是,没有办法。

现在,如果目的只是在创建 Activity 时避免 NPE,对于 Robolectric 版本 <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);

另一个变体可能是 create your own ShadowAudioManager处理 registerMediaButtonEventReceiver 或使用正确的上下文初始化,因为 current one不会那样做,但我实际上还没有尝试过。

关于android - Robolectric 中的 getSystemService 返回具有空上下文的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26021305/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com