现在的位置: 首页 > 综合 > 正文

android 中junit的使用说明

2018年05月07日 ⁄ 综合 ⁄ 共 1660字 ⁄ 字号 评论关闭

        在javase/ee 的开发中,我们对业务方法的测试一般使用“main函数”的方法,也可以使用junit的方法。在android环境下,由于程序运行在Dalvik虚拟机上,我们无法在业务类中使用“main函数”的方式进行测试了。


        android下junit测试框架,实际上是先app打包成apk上传到虚拟机,然后给模拟器发送一些指令来完成测试。


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

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.       package="hb.learn.junit"  
  4.       android:versionCode="1"  
  5.       android:versionName="1.0">  
  6.     <uses-sdk android:minSdkVersion="8" />  
  7.     <application android:icon="@drawable/icon" android:label="@string/app_name">  
  8.       
  9.         <!-- 在本应用中导入需要使用的包,放在application里面activity外面 -->  
  10.         <uses-library android:name="android.test.runner" />  
  11.           
  12.         <activity android:name=".JunitTestActivity"  
  13.                   android:label="@string/app_name">  
  14.             <intent-filter>  
  15.                 <action android:name="android.intent.action.MAIN" />  
  16.                 <category android:name="android.intent.category.LAUNCHER" />  
  17.             </intent-filter>  
  18.         </activity>  
  19.           
  20.     </application>  
  21.       
  22.     <!-- 记住这个一要放在application外面,不然会出现配置错误 信息 -->  
  23.     <instrumentation android:name="android.test.InstrumentationTestRunner"  
  24.         android:targetPackage="hb.learn.junit" android:label="Tests for My App" />  
  25. </manifest>  

上面targetPackage指定的包要和应用的package相同(即AndroidManifest.xml中 manifest节点中的package)。android中,app程序是根据报名区分的。


第二步:编写单元测试代码(选择要测试的方法,右键点击“Run As”--“Android Junit Test” ):

  1. import android.test.AndroidTestCase;  
  2. import android.util.Log;  
  3. public class XMLTest extends AndroidTestCase {  
  4.      public void testSomething() throws Throwable {  
  5.         Assert.assertTrue(1 + 1 == 3);  
  6.    

抱歉!评论已关闭.