qileilove

blog已经转移至github,大家请访问 http://qaseven.github.io/

Android学习笔记之如何对应用进行单元测试

开发环境:
  Win XP + eclipse-jee-helios(版本号3.6) + ADT(版本10.0.1) + Android SDK(版本10);
  模拟器及真机测试环境:Android2.2
  在Android软件的开发过程中,可以使用Junit测试框架。在Junit中可以得到组件,可以模拟发送事件和测试程序处理的正确性。
  第一步:在新建项目中,创建待测试的业务类,在cn.hao.service包中,代码如下:
package cn.hao.service;
//业务类,待测试的两个方法
public class PersonaService {
public void save(String username){
String sub = username.substring(6);
}
public int add(int a,int b){
return a+b;
}
}
  说明:对于save()方法,如果参数为null,那么这个方法会发生错误;对add()方法,我们测试相加返回的相加结果是否正确。
  第二步:为应用引进单元测试环境
  在AndroidManifest.xml中加入如下代码:
  <uses-library android:name="android.test.runner"/>
  <instrumentation android:name="android.test.instrumentationTestRunner"
  android:targetPackage="cn.hao.JunitTest" android:label="Test for My App" />
  引入的位置如下:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="cn.hao.JunitTest"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" />
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name="cn.hao.test.MainActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<uses-library android:name="android.test.runner"/>
</application>
<instrumentation android:name="android.test.instrumentationTestRunner"
android:targetPackage="cn.hao.JunitTest" android:label="App Test"
/>
</manifest>
  说明:在项目中使用单元测试,就是检查程序及处理结果的正确性。
 第三步:新建一个类,测试业务类,代码如下:
package cn.hao.junit;
import junit.framework.Assert;
import cn.hao.service.PersonaService;
import android.test.AndroidTestCase;
public class PersonServiceTest extends AndroidTestCase {
public void testSave() throws Exception {
PersonaService service = new PersonaService();//new出测试对象
service.save(null);
}
public void testAdd() throws Exception {
PersonaService service = new PersonaService();
int actual = service.add(1, 2);
Assert.assertEquals(3, actual);
}
}
 
 注意:该类需继承单元测试框架父类android.test.AndroidTestCase类,测试方法最好是抛出异常给测试框架。方法Assert.assertEquals(3, actual)中参数3是期望(理论上)返回的果,actual是实际上返回的结果。
  第四步:运行测试类
  在大纲OutLine视图中,右击测试方法->Run As->Android Junit Test,会将项目自动部署到模拟器上,测试的结果会以颜色的形式显示,绿色表示方法正确,否则该方法不正确,Eclipse会给出详细的说明,根据帮助文档可以查看相应的错误信息。
  如测试上述testSave()方法时,会给出如下提示:
  当然,save()从第六位开始取子字符串,但是该方法现在的参数为null,会发生空指针异常。

posted on 2014-09-19 09:55 顺其自然EVO 阅读(280) 评论(0)  编辑  收藏 所属分类: 测试学习专栏


只有注册用户登录后才能发表评论。


网站导航:
 
<2014年9月>
31123456
78910111213
14151617181920
21222324252627
2829301234
567891011

导航

统计

常用链接

留言簿(55)

随笔分类

随笔档案

文章分类

文章档案

搜索

最新评论

阅读排行榜

评论排行榜