android Junit

1.测试类需要继承AndroidTestCase

2.添加相关测试配置文件

AndroidManifest.xml文件中:

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
 3     package="com.example.junit"
 4     android:versionCode="1"
 5     android:versionName="1.0" >
 6 
 7     <!-- 指令集需要在manifest的节点下 -->
 8 
 9     <instrumentation
10         android:name="android.test.InstrumentationTestRunner"
11         android:label="Test My app"
12         android:targetPackage="com.example.junit" >
13     </instrumentation>
14 
15     <uses-sdk
16         android:minSdkVersion="8"
17         android:targetSdkVersion="19" />
18 
19     <application
20         android:allowBackup="true"
21         android:icon="@drawable/ic_launcher"
22         android:label="@string/app_name"
23         android:theme="@style/AppTheme" >
24       <!--   在application节点下,使用的函数库 -->
25         <uses-library android:name="android.test.runner"/>
26         <activity
27             android:name="com.example.junit.MainActivity"
28             android:label="@string/app_name" >
29             <intent-filter>
30                 <action android:name="android.intent.action.MAIN" />
31 
32                 <category android:name="android.intent.category.LAUNCHER" />
33             </intent-filter>
34         </activity>
35     </application>
36 
37 </manifest>

然后运行测试方法,如果是绿色条,说明测试的结果为正确。红色表示测试出现问题。

 1 package com.example.test;
 2 
 3 import com.example.service.Calcservice;
 4 
 5 import android.test.AndroidTestCase;
 6 
 7 public class TestAndroidService extends AndroidTestCase {
 8     //测试抛出异常
 9     public void testAdd() throws Exception{
10         Calcservice calcservice = new Calcservice();
11         int result=calcservice.add(3,5);
12         assertEquals(8, result);
13     }
14 }

2 也可以用file  新建一个androidtest项目,将需要测试的工程添加进去。

原文地址:https://www.cnblogs.com/danwuxinbolg/p/4830958.html