Android单元测试

Android实现单元测试步骤

  1、编写一个测试类

1 package com.example.layouttest;
2 
3 public class Case {
4     public int add(int x,int y) {
5         return x + y;
6     }
7 }

 

  2、编写一个java类继承AndroidTestCase类

 1 package com.example.layouttest;
 2 
 3 import android.test.AndroidTestCase;
 4 
 5 public class CaseTest extends AndroidTestCase{
 6     
 7     public void addTest(){
 8         
 9         Case c = new Case();
10         
11         int r = c.add(1, 2);
12         assertEquals(3, r);
13     }
14 }

  

  3.在清单文件AndroidManifest.xml中,配置instrumentation和uses-library

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
 3     package="com.example.layouttest"
 4     android:versionCode="1"
 5     android:versionName="1.0" >
 6 
 7     <uses-sdk
 8         android:minSdkVersion="19"
 9         android:targetSdkVersion="19" />
10     
     <!--表示我要测试那一个工程,下面targetPackage指定了测试那一个包--> 11 <instrumentation 12 android:name="android.test.InstrumentationTestRunner" 13 android:targetPackage="com.example.layouttest" /> 14 15 <application 16 android:allowBackup="true" 17 android:icon="@drawable/ic_launcher" 18 android:label="@string/app_name" 19 android:theme="@style/AppTheme" >

        <!--表示使用了Android中的函数库--> 20 <uses-library android:name="android.test.runner" /> 21 <activity 22 android:name=".MainActivity" 23 android:label="@string/app_name" > 24 <intent-filter> 25 <action android:name="android.intent.action.MAIN" /> 26 27 <category android:name="android.intent.category.LAUNCHER" /> 28 </intent-filter> 29 </activity> 30 </application> 31 32 </manifest>

 如果忘记了清单文件中的红色标记的代码时,可以创建一个Android的测试工程,然后打开测试工程的清单文件就可以找到了