android基础知识12:android自动化测试04—Robotium:实例(上)

来源:互联网 发布:gta4渣优化 编辑:程序博客网 时间:2024/05/21 17:29

前文已经对基于junit的android测试框架有了一个大概的介绍,下面我们对activity测试进行分析。

       本文主要举两个基于Robotium的activity测试例子,一个是测试单个activity,一个测试多个activity。

1、Robotium概述

首先,我们来了解一下android的测试类的层次结构:


        可以看出android中的测试方法主要有AndroidTextCase和InstrumentationTextCase。在这篇文章中,我将介绍Instrumentation这种测试方法,那么什么是Instrumentation?
        Instrumentation和Activity有点类似,只不过Activity是需要一个界面的,而Instrumentation并不是这样的,我们可以将它理解为一种没有图形界面的,具有启动能力的,用于监控其他类(用Target Package声明)的工具类。

2、单个activity测试例子

2.1普通测试

        我想大家在安装完robotium后,都会试试noteslist 这个例子吧。这个是官网提到的例子
首先打开noteslist 源码
\samples\android-7\NotePad 
再打开noteslisttest 源码
可以从上面下载 http://code.google.com/p/robotium/downloads/list/ExampleTestProject_v2.3.zip
要做一点修改。 因为noteslist是在androidV21开发的,而我的测试代码是V23的。我们最好要改成一致的。
修改 noteslisttest 下的AndroidManifest.xml
<uses-sdk android:minSdkVersion="9" /> 
改成<uses-sdk android:minSdkVersion="7" /> 
 
这两个数字表示什么意思呢?
7--androidV21,9--androidV23,最低版本是3--AndroidV15.
大家按顺序排就知道哪个数字对应的版本了
 
然后在 noteslisttest 右击选中Properties--Android,选中AndroidV21
这样noteslisttest 里带的android jar 由android2.3 变为android2.1
 
再说一个配置,我觉得也很重要
还是在AndroidManifest.xml 里
<instrumentation android:targetPackage="com.example.android.notepad" android:name="android.test.InstrumentationTestRunner" />  
红色加粗的字符串表示我们要测试代码的package
 
OK,这样我们就弄好代码了。 我们只需要执行Run As--Android Junit test
 
下面我们看看 noteslisttest 里的具体代码,看看它是怎么测试的

[java] view plaincopy
  1. private Solo solo;  
  2.   
  3.     // 告知系统我要测试的app是什么  
  4.     public NotePadTest() {  
  5.         super("com.example.android.notepad", NotesList.class);  
  6.           
  7.     }  
  8.       
  9.     //打开noteslist   
  10.      public void setUp() throws Exception {  
  11.          solo = new Solo(getInstrumentation(), getActivity());  
  12.           }  
  13.   
  14.        
  15.      @Smoke  
  16.      public void testAddNote() throws Exception {  
  17.          solo.clickOnMenuItem("Add note");  
  18.          solo.assertCurrentActivity("Expected NoteEditor activity""NoteEditor"); //Assert that NoteEditor activity is opened  
  19.          solo.enterText(0"Note 1"); //In text field 0, add Note 1  
  20.          solo.goBack(); //Go back  
  21.          solo.clickOnMenuItem("Add note"); //Clicks on menu item   
  22.          solo.enterText(0"Note 2"); //In text field 0, add Note 2  
  23.          solo.goBackToActivity("NotesList"); //Go back to first activity named "NotesList"  
  24.          boolean expected = true;  
  25.          boolean actual = solo.searchText("Note 1") && solo.searchText("Note 2");  
  26.          assertEquals("Note 1 and/or Note 2 are not found", expected, actual); //Assert that Note 1 & Note 2 are found  
  27.           
  28.      }  
这是我们第一个case,主要目的是测试添加文本的功能 
clickOnMenuItem(String)
功能是点击Menu按钮,选择文本描述为String的菜单,如我们的例子是"Add note"
assertCurrentActivity(String message,String name)
这个是判断当前的activity是否和我预期的一致
message是描述性的文字
name是指activity的名字
关于如何知道activity 名字,我找了半天的文档,目前的方法是得看源码中的 AndroidManifest.xml--Application label--Application Nodes,在那里我们可以看到所有的activity的name
 
enterText(int index,string text)
index用来标识写到哪个EditText中。如果当前只打开一个EditText,那index=0
text:就是我们要写入的内容
 
goBack() 
相当于手机上的 返回键(back key)
 
goBackToActivity(String name)
返回到指定的activity
 
searchText(String text)
在当前的activity中搜索是否含有text的内容 

[java] view plaincopy
  1. @Smoke   
  2.     public void testEditNote() throws Exception {  
  3.         solo.clickInList(2); // Clicks on the second list line  
  4.         solo.setActivityOrientation(Solo.LANDSCAPE); // Change orientation of activity  
  5.         solo.clickOnMenuItem("Edit title"); // Change title  
  6.         solo.enterText(0" test"); //In first text field (0), add test.   
  7.         solo.goBackToActivity("NotesList");  
  8.         boolean expected = true;  
  9.         boolean actual = solo.searchText("(?i).*?note 1 test"); // (Regexp) case insensitive                                                // insensitive  
  10.         assertEquals("Note 1 test is not found", expected, actual); //Assert that Note 1 test is found  
  11.   
  12.     }  
第二个case,主要是测试编辑功能的
clickInList(int index)
 点击list表的第index行,进入该文本界面
 solo.setActivityOrientation(Solo.LANDSCAPE);
 setActivityOrientation,设置手机屏幕显示方式
 LANDSCAPE:横向显示
 Portrait:竖向显示 

[java] view plaincopy
  1. @Smoke  
  2.      public void testRemoveNote() throws Exception {  
  3.          solo.clickOnText("(?i).*?test.*");   //(Regexp) case insensitive/text that contains "test"  
  4.          solo.clickOnMenuItem("Delete");   //Delete Note 1 test  
  5.          boolean expected = false;   //Note 1 test & Note 2 should not be found  
  6.          boolean actual = solo.searchText("Note 1 test");  
  7.          assertEquals("Note 1 Test is found", expected, actual);  //Assert that Note 1 test is not found  
  8.          solo.clickLongOnText("Note 2");  
  9.          solo.clickOnText("(?i).*?Delete.*");  //Clicks on Delete in the context menu  
  10.          actual = solo.searchText("Note 2");  
  11.          assertEquals("Note 2 is found", expected, actual);  //Assert that Note 2 is not found  
  12.      }  
第三个case,是用来测试删除功能的
 clickOnText(String text)
点击包含该文字的地方
其中text可以用正则表达式表示
(?i)----忽略大小写。默认情况是大小写敏感的。
正则表达式与java保持一致
 
clickLongOnText(String text)
长时间按住所选的文字

这里需要注意:被测apk和测试apk必须使用相同的签名。

2.2 数据驱动测试

        本例与上一例子都是对于单个activity测试,不同的地方在于本例使用的测试数据来源于文件。

被测试代码是简易计算器,代码: /Files/morebetter/android code/AndroidCalculator.rar

1. 数据驱动测试架构
测试数据源:TestData.csv

First ValueSecond Value101.5203
第一个输入框从First Value中读数据
第二个输入框从Second Value中读数据
点击Multiply
比较测试结果和期望结果是否一致,将结果写到文件里

2. 创建数据源文件
格式如上图
3. 把数据源文件上传到Emulator上
在被测试代码中创建res/raw/files文件夹。这样files文件夹就能被上传到Emulator上了
用Eclipse—Run As—Android Application 运行被测试代码
在Eclipse上加载DDMS,点击File Exploer,浏览Emulator-5554的所有文件


打开/data/data/com.calculator/files, 点击右侧上传到device的按钮,将csv文件上传到emulator上

4. 编辑测试case, 代码为:/Files/morebetter/android code/AndroidCalculatorTestApk.rar

5. 运行测试case
6. 将测试结果写到文件里,该文件存放在/data/data/com.calculator/files 下面
7. 将测试结果导入到本地电脑中

3、多个activity测试

        在Android SDK中“Resources”-“Tutorials”下有“Notepad Tutorial”和“Activity Testing”两个项目,一个示例是指导你如何快速开发一个Android小程序,一个是指导你如何对项目进行测试,两个项目都适合在入门的时候好好学习。 
       其中的“Activity Testing”是对“Samples”-“Spinner”项目进行测试,其中包含了UI测试、状态破坏和状态恢复测试。这个项目只有一个Activity,测试起来也不麻烦,细心阅读文档就可以完成。但是一个程序只有一个Activity应该是很难遇见的吧,那么应该对多活动(Multi Activities)的程序进行测试呢? 
       其实我这也是随便整整,大家随便看看。 

        在查看SDK关于测试的章节后,有疑问如下: 
测试Activity、Service、Provider都是自动化的,那么我们如何控制运行过程? 
如何在界面模拟操作,如点击按钮,输入文字内容等等。 

        新建一个项目,项目名为Login,包名为com.vruc.android.login,程序名为Login,活动名为AuthenticateActivity;同时添加一个项目名为LoginTest,包名为com.vruc.android.login.test,程序名为LoginTest的测试项目。 
   完整的Login项目: 
   1.更改main.xml文件名为login.xml,更改代码为下: 

[html] view plaincopy
  1. <?xml version="1.0" encoding="utf-8"?>    
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    
  3.     android:orientation="vertical" android:layout_width="fill_parent"    
  4.     android:layout_height="fill_parent">    
  5.     <EditText android:id="@+id/username_field"    
  6.         android:layout_height="wrap_content" android:layout_width="match_parent"></EditText>    
  7.     <EditText android:id="@+id/password_field"    
  8.         android:layout_height="wrap_content" android:layout_width="match_parent"></EditText>    
  9.     <Button android:text="Login" android:id="@+id/login_button"    
  10.         android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>    
  11. </LinearLayout>    
2.打开AuthenticateActivity.java文件,为“@+id/login_button”添加点击事件,具体代码就是向WelcomeActivity传递当前“@+id/username_field”中的输入文字并结束当前activity,具体代码为下: 

[java] view plaincopy
  1. public class AuthenticateActivity extends Activity {  
  2.     /** Called when the activity is first created. */  
  3.     @Override  
  4.     public void onCreate(Bundle savedInstanceState) {  
  5.         super.onCreate(savedInstanceState);  
  6.         setContentView(R.layout.login);  
  7.         Button login = (Button) findViewById(R.id.login_button);  
  8.         login.setOnClickListener(new OnClickListener() {  
  9.             @Override  
  10.             public void onClick(View v) {  
  11.                 Intent i = new Intent(AuthenticateActivity.this,WelcomeActivity.class);  
  12.                 i.putExtra(ACCOUNT_SERVICE,((EditText) findViewById(R.id.username_field)).getText().toString());  
  13.                 startActivity(i);  
  14.                 finish();  
  15.             }  
  16.         });  
  17.     }  
  18. }  
3.在layout目录下添加新文件welcome.xml,更改代码为下:

[html] view plaincopy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:orientation="vertical" android:layout_width="fill_parent"  
  4.     android:layout_height="fill_parent">  
  5.     <TextView android:id="@+id/welcome_message"  
  6.         android:layout_width="wrap_content" android:layout_height="wrap_content"  
  7.         android:textSize="15pt"></TextView>  
  8. </LinearLayout>  
 4.添加新的WelcomeActivity.java文件并在AndroidMainifest.xml中注册,重写onCreate事件,具体代码就是为“@+id/welcome_message”赋值,从LoginActivity中传递过来的“@+id/username_field”的值,具体代码为下:  

[java] view plaincopy
  1. public class WelcomeActivity extends Activity {  
  2.     @Override  
  3.     public void onCreate(Bundle savedInstanceState) {  
  4.         super.onCreate(savedInstanceState);  
  5.         setContentView(R.layout.welcome);  
  6.         Intent i = this.getIntent();  
  7.         ((TextView)findViewById(R.id.welcome_message)).setText(i.getStringExtra(ACCOUNT_SERVICE));  
  8.     }  
现在可以运行一下Login项目,可以发现填写在“@+id/username_field”中的文字在点击“@+id/login_button”按钮后出现在了WelcomeActivity中。 

   完整的LoginTest项目 
   1.添加LoginTest.java文件,继承类为android.test.InstrumentationTestCase 
   2.完整LoginTest.java中测试代码:

[java] view plaincopy
  1. public static final String TEST_USERNAME = "TEST_USERNAME";  
  2. public static final String TEST_PASSWORD = "TEST_PASSWORD";  
  3.   
  4. public void testUserLogin() {  
  5.   
  6.     // 注册最开始的活动并运行  
  7.     Instrumentation instrumentation = getInstrumentation();  
  8.     ActivityMonitor monitor = instrumentation.addMonitor(  
  9.             AuthenticateActivity.class.getName(), nullfalse);  
  10.   
  11.     // 运行活动  
  12.     Intent intent = new Intent(Intent.ACTION_MAIN);  
  13.     intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
  14.     intent.setClassName(instrumentation.getTargetContext(), AuthenticateActivity.class.getName());  
  15.     instrumentation.startActivitySync(intent);  
  16.       
  17.     // 等待Authenticate活动开始  
  18.     Activity currentActivity = getInstrumentation().waitForMonitorWithTimeout(monitor, 5);  
  19.     assertTrue(currentActivity != null);  
  20.   
  21.     // 自动输入预定的用户名  
  22.     View currentView = currentActivity.findViewById(com.vruc.android.login.R.id.username_field);  
  23.     assertTrue(currentView != null);  
  24.     TouchUtils.clickView(this, currentView);  
  25.     instrumentation.sendStringSync(TEST_USERNAME);  
  26.   
  27.     // 自动输入预定的密码  
  28.     currentView = currentActivity.findViewById(com.vruc.android.login.R.id.password_field);  
  29.     assertTrue(currentView != null);  
  30.     TouchUtils.clickView(this, currentView);  
  31.     instrumentation.sendStringSync(TEST_PASSWORD);  
  32.   
  33.     // 移除当前活动监视,注册新的活动监视,要在还没有按下按钮前准备  
  34.     instrumentation.removeMonitor(monitor);  
  35.     monitor = instrumentation.addMonitor(WelcomeActivity.class.getName(), nullfalse);  
  36.   
  37.     // 自动点击登陆按钮  
  38.     currentView = currentActivity.findViewById(com.vruc.android.login.R.id.login_button);  
  39.     assertTrue(currentView != null);  
  40.     TouchUtils.clickView(this, currentView);  
  41.   
  42.     // 等待Welcome活动开始  
  43.     currentActivity = getInstrumentation().waitForMonitorWithTimeout(monitor, 5);  
  44.   
  45.     currentView = currentActivity.findViewById(com.vruc.android.login.R.id.welcome_message);  
  46.     assertTrue(currentView != null);  
  47.     assertEquals(TEST_USERNAME, ((TextView) currentView).getText().toString());  
  48.   
  49. }  
运行测试程序后可以发现testUserLogin顺利通过,也可以在模拟器查看具体的运行过程,就像你新手操作模拟器一般。

4、Activity 启动 Instrumentation 测试 

和startActivity 及 startService类似
在activity中 启动Instrumentation  以便调用运行测试项目 ActivityInstrumentationTestCase2
可以尝试如下代码实现
startInstrumentation(new ComponentName("com.example.test", "android.test.InstrumentationTestRunner"), null, null);

5、从Intent中获取数据

大多数Activity在启动时,都会从Intent中获取一些数据。
在使用Robotium测试时,当然也会需要从Activity中获取数据。
可用的流程为
1。将setUp()方法中的
solo = new Solo(getInstrumentation(), getActivity());
转移到每一个testXXX方法中。
2.在该语句前,可以做Intent的注入,例如

[java] view plaincopy
  1. Intent intent=new Intent();  
  2.   Bundle b=new Bundle();  
  3.   b.putParcelable(Account.class.getName(), account);  
  4.   b.putParcelable(User.class.getName(), user);  
  5.   intent.putExtras(b);  
  6.   setActivityIntent(intent);  
3.需要注意的是,需要将所有有关Activity的操作,放在
solo = new Solo(getInstrumentation(), getActivity());之后,例如
有操作本地Key-Value存储的,需要早solo=   之后执行。否则会引起Activity提前实例化。导致Intent注入失败

参考文献:

android单元测试初探——Instrumentation
Activity 启动 Instrumentation 测试
学习NotesList(Robotium自带的例子)
Android Test - Auto Test Multi Activities
Robotium 数据驱动测试框架


原创粉丝点击