8

单击“记录”按钮时,我正在广播意图。传递一个布尔变量,它显示是否开始录制。生成意图的代码是:

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();

}

我还针对实际意图而不是其影子进行了测试,但结果相同

4

3 回答 3

3

使用 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();

}
于 2012-06-24T03:56:11.387 回答
0

This might not help for the original, but, future people: if you happen to find yourself in this situation - firstly check your constants and intent filters are distinct so that an unintentional broadcast is not received by your receiver. Several times I've spent longer than I care to admit with that issue!

于 2016-11-15T12:45:46.700 回答
0

in Robolectri

shadowOf(ApplicationProvider.<Application>getApplicationContext()).getBroadcastIntents();
于 2021-03-03T10:13:33.927 回答