单击“记录”按钮时,我正在广播意图。传递一个布尔变量,它显示是否开始录制。生成意图的代码是:
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();
}
我还针对实际意图而不是其影子进行了测试,但结果相同