android – 如何测试已广播的意图

当点击“记录”按钮时,我正在广播一个意图.传递一个布尔变量,显示录制是否已开始.生成意图的代码是:
Intent recordIntent = new Intent(ACTION_RECORDING_STATUS_CHANGED);
recordIntent.putExtra(RECORDING_STARTED,getIsRecordingStarted());
sendBroadcast(recordIntent);

为了测试这段代码,我在测试中注册了一个接收器.收到意图但传递的变量不一样.如果我调试代码,我可以看到该值与发送时相同,但是当我得到它时,它的值不一样.

@Test
public void pressingRecordButtonOnceGenerateStartRecordingIntent()
        throws Exception {
    // Assign
    AppActivity activity = new AppActivity();
    activity.onCreate(null);
    activity.onResume();

    activity.registerReceiver(new BroadcastReceiver() {
        @Override
        public void onReceive(Context arg0,Intent intent) {
            // Assert
            ShadowIntent shadowIntent = Robolectric.shadowOf(intent);
            assertThat(shadowIntent
                    .hasExtra(AppActivity.RECORDING_STARTED),equalTo(true));
            Boolean expected = true;
            Boolean actual = shadowIntent.getExtras().getBoolean(
                    AppActivity.RECORDING_STARTED,false);
            assertThat(actual,equalTo(expected));

        }
    },new IntentFilter(
            AppActivity.ACTION_RECORDING_STATUS_CHANGED));

    ImageButton recordButton = (ImageButton) activity
            .findViewById(R.id.recordBtn);

    // Act
    recordButton.performClick();
    ShadowHandler.idleMainLooper();

}

我也测试了实际的意图,而不是它的阴影,但结果相同

解决方法

使用get()而不是getBoolean()为我工作.
public void pressingRecordButtonOnceGenerateStartRecordingIntent()
        throws Exception {
    // Assign
    BreathAnalyzerAppActivity activity = new AppActivity();
    activity.onCreate(null);
    activity.onResume();

    activity.registerReceiver(new BroadcastReceiver() {
        @Override
        public void onReceive(Context arg0,Intent intent) {
            // Assert
            assertThat(intent
                    .hasExtra(AppActivity.RECORDING_STARTED),equalTo(true));
            Boolean expected = true;
            Boolean actual = (Boolean)intent.getExtras().get(
                    AppActivity.RECORDING_STARTED);
            assertThat(actual,equalTo(expected));


        }
    },new IntentFilter(
            AppActivity.ACTION_RECORDING_STATUS_CHANGED));

    ImageButton recordButton = (ImageButton) activity
            .findViewById(R.id.recordBtn);

    // Act
    recordButton.performClick();
    ShadowHandler.idleMainLooper();

}

相关文章

Android 如何解决dialog弹出时无法捕捉Activity的back事件 在...
Android实现自定义带文字和图片的Button 在Android开发中经常...
Android 关于长按back键退出应用程序的实现最近在做一个Andr...
android自带的时间选择器只能精确到分,但是对于某些应用要求...