我點擊「記錄」按鈕時播放意圖。傳遞一個布爾變量,它顯示記錄是否開始。生成意圖的代碼是:如何測試一個意圖已被播出
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();
}
我也與實際的意圖,而不是它的身影,但同樣的結果
是否真的會調用'BroadcastReceiver'中的任何'assert'?我嘗試了'assertThat(intent.hasExtra(AppActivity.RECORDING_STARTED),equalTo(true));'和'assertThat(intent.hasExtra(AppActivity.RECORDING_STARTED),equalTo(false));'並且我的測試並沒有失敗案例。所以,我的猜測是,這些斷言聲明從來沒有真正被調用。 – iRuth
不,它不會被調用。 – zavidovych