编写: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();