如何测试已广播的意图

got*_*oto 8 android unit-testing robolectric

当点击"记录"按钮时,我正在广播一个意图.传递一个布尔变量,显示录制是否已开始.生成意图的代码是:

Intent recordIntent = new Intent(ACTION_RECORDING_STATUS_CHANGED);
recordIntent.putExtra(RECORDING_STARTED, getIsRecordingStarted());
sendBroadcast(recordIntent);
Run Code Online (Sandbox Code Playgroud)

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

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

}
Run Code Online (Sandbox Code Playgroud)

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

got*_*oto 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();

}
Run Code Online (Sandbox Code Playgroud)

  • “BroadcastReceiver”中的任何“assert”实际上是否被调用?我尝试了 `assertThat(intent.hasExtra(AppActivity.RECORDING_STARTED), equalTo(true));` 和 `assertThat(intent.hasExtra(AppActivity.RECORDING_STARTED), equalTo(false));` 并且我的测试都没有失败案例。所以,我的猜测是这些断言语句实际上从未被调用。 (2认同)