我正在播放"记录"单击按钮。传递一个布尔变量,显示录制是否已开始。生成意图的代码是:
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();
}
我还测试了实际意图而不是阴影,但结果相同
答案 0 :(得分: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();
}
答案 1 :(得分:0)
这可能对原始的,但未来的人没有帮助:如果您碰巧发现自己处于这种情况 - 首先检查您的常量和意图过滤器是否截然不同,以便接收者不会收到无意的广播。有好几次我花的时间比我更愿意承认这个问题!
答案 2 :(得分:0)
在 Robolectri 中
shadowOf(ApplicationProvider.<Application>getApplicationContext()).getBroadcastIntents();