如何测试广播的意图

当点击“记录”按钮时,我播放了一个意图。 传递一个布尔变量,它显示记录是否开始。 生成意图的代码是:

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

}

这可能对原来的,但未来的人没有帮助:如果你碰巧遇到这种情况 - 首先检查你的常量和意图过滤器是不同的,这样你的接收器就不会收到无意的广播。 我多次花费的时间超过了我关心的承认这个问题!

链接地址: http://www.djcxy.com/p/10865.html

上一篇: How to test that an intent has been broadcasted

下一篇: Is Ruby on Rails with Draper or Apotomo a MVVM?