对android应用进行单元测试使用单元测试框架

第一篇博文,是关于对android应用进行单元测试的,在android应用开发中很经常使用的,能够测试android应用的代码测试、检测程序处理的正确性,在一个应用开发中单元测试框架是不可必少的,下面经过一个例子来进行讲解:android

个人思路:app

首先建立个单元测试项目,再在项目中建立一个被测试的类文件,经过单元测试对被测试类里面的一个方法进行测试,为了好解释就写给简单的了,框架

代码以下:ide

  
  
           
  
  
  1. package com.betest.test;  
  2.  
  3. public class betest {  
  4.  
  5.     public int test() {  
  6.         String in = "test";  
  7.         int b = new Integer(in);  
  8.           
  9.     }  

 

从上面看代码执行的过程当中会出错吧单元测试

下面编辑测试文件:测试

由于是在android项目中使用单元测试,首先须要在项目功能清单文件(也就是AndroidMainfest.xml)中加入调用测试类库。spa

代码以下:日志

 

  
  
           
  
  
  1. <?xml version="1.0" encoding="utf-8"?> 
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android" 
  3.       package="com.test.test" 
  4.       android:versionCode="1" 
  5.       android:versionName="1.0"> 
  6.     <application android:icon="@drawable/icon" android:label="@string/app_name"> 
  7.         <!--调用测试类库--> 
  8.         <uses-library android:name="android.test.runner" /> 
  9.         <activity android:name=".MainActivity" 
  10.                   android:label="@string/app_name"> 
  11.             <intent-filter> 
  12.                 <action android:name="android.intent.action.MAIN" /> 
  13.                 <category android:name="android.intent.category.LAUNCHER" /> 
  14.             </intent-filter> 
  15.         </activity> 
  16.  
  17.     </application> 
  18.     <uses-sdk android:minSdkVersion="8" /> 
  19.     <!--  包名要去测试文档包名相同 --> 
  20.     <instrumentation android:name="android.test.InstrumentationTestRunner" 
  21.   android:targetPackage="com.test.test" /> 
  22. </manifest>  

上面的代码中也就是加入了 xml

 <uses-library android:name="android.test.runner" />utf-8

<instrumentation android:name="android.test.InstrumentationTestRunner"
  android:targetPackage="com.test.test"  />

这两句话。

开始建立测试类,建立个单元测试方法,代码以下:

 

  
  
           
  
  
  1. package com.test.test;  
  2.  
  3. import junit.framework.Assert;  
  4. import com.betest.test;
  5. import android.test.AndroidTestCase;  
  6. import android.util.Log;  
  7.  
  8. public class PersonServiceTest extends AndroidTestCase {  
  9.       
  10.  
  11.     public void testtest() throws Throwable{  
  12.         PersonService service = new PersonService();  
  13.         service.test();//检验save()方法运行是否正常  
  14.                                   
  15.     }  

到这里代码已经写完,下面就开始进行测试了,在outline里面找到相应的单元测试方法,右键 找到 Android Junit Test 在日志文件中就能够看到错误缘由了。

 

第一次写,有什么很差的地方,请指点指点。谢谢