首页 > 系统 > Android > 正文

Android学习笔记之应用单元测试实例分析

2019-10-24 20:34:22
字体:
来源:转载
供稿:网友

这篇文章主要介绍了Android学习笔记之应用单元测试,结合实例形式较为详细的分析了Android单元测试的实现原理与具体步骤,具有一定参考借鉴价值,需要的朋友可以参考下

本文实例讲述了Android学习笔记之应用单元测试。分享给大家供大家参考,具体如下:

第一步:在AndroidManifest.xml中加入如下两段代码:

 

 
  1. <manifest xmlns:android="http://schemas.android.com/apk/res/android" 
  2. package="com.pccw" 
  3. android:versionCode="1" 
  4. android:versionName="1.0">  
  5. <uses-sdk android:minSdkVersion="8" />  
  6. <application android:icon="@drawable/icon" android:label="@string/app_name">  
  7. <activity android:name=".MainActivity" 
  8. android:label="@string/app_name">  
  9. <intent-filter>  
  10. <action android:name="android.intent.action.MAIN" />  
  11. <category android:name="android.intent.category.LAUNCHER" />  
  12. </intent-filter>  
  13. </activity>  
  14. <!—添加代码1-->  
  15. <uses-library android:name="android.test.runner"/>  
  16. </application>  
  17. <!—添加代码2-->  
  18. <instrumentation android:name="android.test.InstrumentationTestRunner" 
  19. android:targetPackage="com.pccw" android:label="aaa"/>  
  20. </manifest> 

1. 代表把单元测试框架中的一些依赖库引入进来

2. 代表配置单元测试框架的启动装置,启动装置有好几个类,可以选择,一般情况下我们使用上面这个。

3. targetPackage与上面的package相同,代表单元测试框架和当前应用是处于同一个进程中

第二步:编写业务逻辑,即需要被测试的模块

 

 
  1. public class PersonService {  
  2. public void save(String name){  
  3. String sub = name.substring(6);  
  4. }  
  5. public int add(int a, int b){  
  6. return a+b;  
  7. }  

第三步:编写单元测试代码

 

 
  1. public class PersonServiceTest extends AndroidTestCase {  
  2. public void testSave() throws Exception {  
  3. PersonService service = new PersonService();  
  4. service.save(null);  
  5. }  
  6. public void testAdd() throws Exception {  
  7. PersonService service = new PersonService();  
  8. int result = service.add(1, 2);  
  9. Assert.assertEquals(3, result);  
  10. }  

第四步:打开eclipse中的outline窗口,其中会显示单元测试类的所有的方法

Android学习笔记之应用单元测试实例分析

然后想要测试哪个方法,则在哪个测试方法上右键鼠标,选择Run As,然后再选择Android JUnit Test即可,如果有异常或者错误,则会出现如下情况:

Android学习笔记之应用单元测试实例分析

如果是正常的,则会如下:

Android学习笔记之应用单元测试实例分析

希望本文所述对大家Android程序设计有所帮助。


注:相关教程知识阅读请移步到Android开发频道。
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表