如何創建測試活動內生成的Intent內容的Android JUnit測試用例?我該如何單元測試從活動啓動/發送的Intent?
我有一個包含EditText窗口的Activity,當用戶輸入完所需數據後,Activity將Intent發送到IntentService,IntentService記錄數據並繼續執行應用程序進程。下面是我要測試的類中,OnEditorActionListener/PasscodeEditorListener被創建爲一個單獨的類:
public class PasscodeActivity extends BaseActivity {
EditText m_textEntry = null;
PasscodeEditorListener m_passcodeEditorListener = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.passcode_activity);
m_passcodeEditorListener = new PasscodeEditorListener();
m_textEntry = (EditText) findViewById(R.id.passcode_activity_edit_text);
m_textEntry.setTag(this);
m_textEntry.setOnEditorActionListener(m_passcodeEditorListener);
}
@Override
protected void onPause() {
super.onPause();
/*
* If we're covered for any reason during the passcode entry,
* exit the activity AND the application...
*/
Intent finishApp = new Intent(this, CoreService.class);
finishApp.setAction(AppConstants.INTENT_ACTION_ACTIVITY_REQUESTS_SERVICE_STOP);
startService(finishApp);
finish();
}
}
class PasscodeEditorListener implements OnEditorActionListener{
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
PasscodeActivity activity = (PasscodeActivity) v.getTag();
boolean imeSaysGo = ((actionId & EditorInfo.IME_ACTION_DONE)!=0)?true:false;
boolean keycodeSaysGo = ((null != event) &&
(KeyEvent.ACTION_DOWN == event.getAction()) &&
(event.getKeyCode() == KeyEvent.KEYCODE_ENTER))?true:false;
if (imeSaysGo || keycodeSaysGo){
CharSequence seq = v.getText();
Intent guidEntry = new Intent(activity, CoreService.class);
guidEntry.setAction(AppConstants.INTENT_ACTION_PASSCODE_INPUT);
guidEntry.putExtra(AppConstants.EXTRA_KEY_GUID, seq.toString());
activity.startService(guidEntry);
return true;
}
return false;
}
}
我怎樣才能攔截活動產生的兩種可能的對外意圖和驗證其內容是什麼?
感謝
你在使用模擬器嗎?也許我錯過了一些東西,但是難道你不能這樣測試它嗎? – Nick 2012-04-27 00:40:06
我一直在使用模擬器和手機,但我不認爲應該有所不同。我已經看到了很多方法來將Intents注入任何特定的被測活動,但沒有很多方法來觀察輸出。看到另一篇帖子,他們設置了ContextWrapper並攔截了對「startService()」的調用。這適用於第一次通話,但不適用於後續通話。一項活動可以在不關閉的情況下發布多個意圖,我對觀看/測試所有內容感興趣。 – 2012-04-27 03:38:12