編寫:huanglizhuo - 原文:http://developer.android.com/training/activity-testing/activity-functional-testing.html
功能測試包括驗證單個應用中的各個組件是否與使用者期望的那樣(與其它組件)協同工作。比如,我們可以創建一個功能測試驗證在用戶執行UI交互時Activity是否正確啟動目標Activity。
要為Activity創建功能測,我們的測試類應該對ActivityInstrumentationTestCase2進行擴展。與ActivityUnitTestCase不同,ActivityInstrumentationTestCase2中的測試可以與Android系統通信,發送鍵盤輸入及點擊事件到UI中。
要了解一個完整的測試例子可以參考示例應用中的SenderActivityTest.java
。
我們的函數測試目標應該包括:
我們可以這樣實現測試方法:
@MediumTest
public void testSendMessageToReceiverActivity() {
final Button sendToReceiverButton = (Button)
mSenderActivity.findViewById(R.id.send_message_button);
final EditText senderMessageEditText = (EditText)
mSenderActivity.findViewById(R.id.message_input_edit_text);
// Set up an ActivityMonitor
...
// Send string input value
...
// Validate that ReceiverActivity is started
...
// Validate that ReceiverActivity has the correct data
...
// Remove the ActivityMonitor
...
}
測試會等待匹配的Activity啟動,如果超時則會返回null。如果ReceiverActivity啟動了,那麼先前配置的ActivityMoniter就會收到一次碰撞(Hit)。我們可以使用斷言方法驗證ReceiverActivity是否的確啟動了,以及ActivityMoniter記錄的碰撞次數是否按照預想地那樣增加。
為了在應用中監視單個Activity我們可以註冊一個ActivityMoniter。每當一個符合要求的Activity啟動時,系統會通知ActivityMoniter,進而更新碰撞數目。
通常來說要使用ActivityMoniter,我們可以這樣:
下面是一個例子:
// Set up an ActivityMonitor
ActivityMonitor receiverActivityMonitor =
getInstrumentation().addMonitor(ReceiverActivity.class.getName(),
null, false);
// Validate that ReceiverActivity is started
TouchUtils.clickView(this, sendToReceiverButton);
ReceiverActivity receiverActivity = (ReceiverActivity)
receiverActivityMonitor.waitForActivityWithTimeout(TIMEOUT_IN_MS);
assertNotNull("ReceiverActivity is null", receiverActivity);
assertEquals("Monitor for ReceiverActivity has not been called",
1, receiverActivityMonitor.getHits());
assertEquals("Activity is of wrong type",
ReceiverActivity.class, receiverActivity.getClass());
// Remove the ActivityMonitor
getInstrumentation().removeMonitor(receiverActivityMonitor);
如果Activity有一個EditText,我們可以測試用戶是否可以給EditText對象輸入數值。
通常在ActivityInstrumentationTestCase2中給EditText對象發送串字符,我們可以這樣做:
比如:
// Send string input value
getInstrumentation().runOnMainSync(new Runnable() {
@Override
public void run() {
senderMessageEditText.requestFocus();
}
});
getInstrumentation().waitForIdleSync();
getInstrumentation().sendStringSync("Hello Android!");
getInstrumentation().waitForIdleSync();