gpt4 book ai didi

android - 如何测试 Intent 是否已广播

转载 作者:塔克拉玛干 更新时间:2023-11-02 18:58:45 26 4
gpt4 key购买 nike

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

Intent recordIntent = new Intent(ACTION_RECORDING_STATUS_CHANGED);
recordIntent.putExtra(RECORDING_STARTED, getIsRecordingStarted());
sendBroadcast(recordIntent);

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

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

}

我也测试了实际 Intent 而不是它的影子,但结果相同

最佳答案

使用 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 - 如何测试 Intent 是否已广播,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11076766/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com