2012-06-18 22 views
7

我點擊「記錄」按鈕時播放意圖。傳遞一個布爾變量,它顯示記錄是否開始。生成意圖的代碼是:如何測試一個意圖已被播出

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

} 

我也與實際的意圖,而不是它的身影,但同樣的結果

回答

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

} 
+2

是否真的會調用'BroadcastReceiver'中的任何'assert'?我嘗試了'assertThat(intent.hasExtra(AppActivity.RECORDING_STARTED),equalTo(true));'和'assertThat(intent.hasExtra(AppActivity.RECORDING_STARTED),equalTo(false));'並且我的測試並沒有失敗案例。所以,我的猜測是,這些斷言聲明從來沒有真正被調用。 – iRuth

+0

不,它不會被調用。 – zavidovych

0

這可能不利於原始,但是,未來的人:如果你碰巧發現自己處於這種情況 - 首先檢查,這樣無意廣播不是由你的接收機收到您的常量和意圖過濾器是不同的。我多次花費的時間超過了我關心的承認這個問題!

相關問題