今天突然对Android的自动化测试有点儿感兴趣,google了下,发现自动化测试的工具还真不少,有Monkey,MonkeyRunner,Robotium等太多了,前段时间也看到了 风泊海上 写的《Android自动化测试之Robotium学习》的博文,呵呵感觉也不错,但是我自己也喜欢自己总结,做下笔记哈。
<a href="http://blog.51cto.com/attachment/201210/171811619.png" target="_blank"></a>
下载完成后,可以看到如下
<a href="http://blog.51cto.com/attachment/201210/172147160.png" target="_blank"></a>
将ExampleTestProject_v3.4.1.zip导入到eclipse中,可以看到有两个多了两个项目。NotepadTest是测试项目,测试Notepad的,我们可以直接运行Android JUnit Test 查看运行效果,即可以看到模拟器上面正在自动测试。
<a href="http://blog.51cto.com/attachment/201210/172147108.png" target="_blank"></a>
<a href="http://blog.51cto.com/attachment/201210/172147438.png" target="_blank"></a>
现在我们自己一步步的完整的写个程序进行自动化测试。
1、首先创建一个hellorobotium的project,里面内容简单,只需要一个输入框,和一个按钮即可。逻辑代码直接下载源码看。如下图
<a href="http://blog.51cto.com/attachment/201210/172546368.png" target="_blank"></a>
2、现在开始创建测试项目。右击新建,找到Android Test Project
<a href="http://blog.51cto.com/attachment/201210/172835109.png" target="_blank"></a>
然后选中下一步,填写Project name,自己随便取,然后在下一步选择要测试的项目即可。
<a href="http://blog.51cto.com/attachment/201210/173201409.png" target="_blank"></a>
3、创建完成后,添加robotium-solo-3.4.1.jar,如下图所示
<a href="http://blog.51cto.com/attachment/201210/173426497.png" target="_blank"></a>
4、开始编写测试类(Test)
package com.xzw.test;
import com.jayway.android.robotium.solo.Solo;
import com.xzw.example.EditorActivity;
import android.test.ActivityInstrumentationTestCase2;
public class Test extends ActivityInstrumentationTestCase2<EditorActivity>{
private Solo solo;
public Test(){
super(EditorActivity.class);
}
@Override
protected void setUp() throws Exception {
//setUp() is run before a test case is started.
//This is where the solo object is created.
solo = new Solo(getInstrumentation(), getActivity());
}
protected void tearDown() throws Exception {
//tearDown() is run after a test case has finished.
//finishOpenedActivities() will finish all the activities that have been opened during the test execution.
solo.finishOpenedActivities();
/**
* 测试点击事件
*/
public void testClick(){
solo.assertCurrentActivity("进入EditorActivity", "EditorActivity");
try {
Thread.sleep(1000); //休息1秒
} catch (InterruptedException e) {
e.printStackTrace();
}
solo.clickOnEditText(0); //点击输入框
} catch (InterruptedException e) {
// TODO Auto-generated catch block
solo.enterText(0, "xzw"); //往第一个EditText,输入文本。第一个为0
solo.clickOnButton("Click"); //点击按钮
solo.takeScreenshot(); //屏幕截图,并保存到 "/sdcard/Robotium-Screenshots/".
boolean expected = true;
boolean actual = solo.searchText("xx"); //查找含有xx字符的text,如果没有则返回false
//验证预期结果
assertEquals("xx is not found", expected, actual);
}
5、运行android junit test查看运行结果。
<a href="http://blog.51cto.com/attachment/201210/174044920.png" target="_blank"></a>
嘿嘿,搞定是不是很简单啊。
欢迎大家一起学习交流。
本文转自xuzw13 51CTO博客,原文链接:http://blog.51cto.com/xuzhiwei/1019911,如需转载请自行联系原作者