首页 > 系统 > Android > 正文

Android编程之单元测试实例分析

2019-10-24 20:34:26
字体:
来源:转载
供稿:网友
这篇文章主要介绍了Android编程之单元测试,结合具体实例分析了Android单元测试的具体实现步骤与相关注意事项,具有一定参考借鉴价值,需要的朋友可以参考下
 

本文实例讲述了Android编程之单元测试用法。分享给大家供大家参考,具体如下:

在实际开发中,开发android软件的过程需要不断地进行测试。使用Junint测试框架,是正规Android开发的必用技术,在Junint中可以得到组件,可以模拟发送事件和检测程序处理的正确性。单元测试是嵌入到项目中;也可以作为一个单独的项目争对某个具体项目进行测试。

第一步:首先在AndroidManifest.xml中加入下面红色代码:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.lee0000.test" android:versionCode="1" android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
    <uses-library android:name="android.test.runner"/> 
</application>
<use-sdk android:minSdkVersion="6"/>
<instrumentation android:name="android.test.instrumentationTestRunner" android:targetPackage="com.lee0000.test" android:label="Tests"/> 
 ***上面targetPackage指定的包要和应用的package相同。

第二步:编写单元测试代码,一般对将要测试的方法命名testXXX。需要测试的时候选择大纲(Outline视图)选择测试的方法右键点击,选择"Run As" - "Android Junit Test"。

例:

项目结构:

Android编程之单元测试实例分析

AndroidManifest.xml文件:
 

  1. <?xml version="1.0" encoding="utf-8"?> 
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android" 
  3.  package="com.lee0000.test" 
  4.  android:versionCode="1" 
  5.  android:versionName="1.0" > 
  6.  <uses-sdk android:minSdkVersion="15" /> 
  7.  <application 
  8.   android:icon="@drawable/ic_launcher" 
  9.   android:label="@string/app_name" > 
  10.   <activity 
  11.    android:name=".JUintTestActivity" 
  12.    android:label="@string/app_name" > 
  13.    <intent-filter> 
  14.     <action android:name="android.intent.action.MAIN" /> 
  15.     <category android:name="android.intent.category.LAUNCHER" /> 
  16.    </intent-filter> 
  17.   </activity> 
  18.  <uses-library android:name="android.test.runner" />   
  19.  </application> 
  20.  <instrumentation 
  21.   android:name="android.test.InstrumentationTestRunner" 
  22.   android:targetPackage="com.lee0000.test" android:label="Tests"/>  
  23. </manifest>  
?

定义测试的两个方法:
 

  1. public class testclass { 
  2.  public void str(String s){ 
  3.   System.out.println(s.substring(6)); 
  4.  } 
  5.  public int add(int a,int b){ 
  6.   return a+b; 
  7.  } 
  8. }  
?

一般继承的是AndroidTestCase,测试的时候就是测试这两个方法,如果在对应方法中选择"Run As" - "Android Junit Test"时出错,可以右键Test类,选择"Run as" - "Run Configurations",在 Instrumentation runner中选择:
 

  1. import junit.framework.Assert; 
  2. import android.test.AndroidTestCase; 
  3. public class Test extends AndroidTestCase{ 
  4.  public void teststr() throws Exception{ 
  5.   testclass tc = new testclass(); 
  6.   tc.str("null"); 
  7.  } 
  8.  public void testadd(){ 
  9.   testclass tc = new testclass(); 
  10.   int t = tc.add(1, 2); 
  11.   Assert.assertEquals(3, t); 
  12.  } 
  13. }  
?

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



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