Android中使用自身攜帶的Junit新建一個測試工程

一、新創建一個Android工程java

package com.shellway.junit;

public class Service {
      public int divide(int a,int b){
          return a/b;
      }
}
Service.java.做爲被測試類
package com.shellway.junit;

import junit.framework.Assert;
import android.test.AndroidTestCase;

public class TestT extends AndroidTestCase {
    public void test1(){
        Service service = new Service();
        System.out.println(service.divide(10, 2));
    }
    public void test2(){
        Service service = new Service();
        System.out.println(service.divide(10, 0));
    }
    public void test3(){
        Service service = new Service();
        Assert.assertEquals(2.5, service.divide(10, 4));
    }
}
TestT繼承AndroidTestCase,做爲測試類
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.shellway.junit"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="16"
        android:targetSdkVersion="21" />
       <instrumentation
        android:targetPackage="com.shellway.junit"
        android:name="android.test.InstrumentationTestRunner" />
    
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <uses-library android:name="android.test.runner" />
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>
AndroidManifest.xml

注意:在配置文件中要加入的內容是:android

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

<uses-library android:name="android.test.runner" />
View Code

而且要注意他們加入的位置。這是一種測試自身工程的方法。shell

另外一種方法是:新建一個Android Junit工程來測試另外的一個工程,這裏須要注意的是創建這個測試工程名的時候不能以Test來命名,否則出現錯誤都很難找出問題所在,下面給出以Test來命名工程的出錯信息。app

相關文章
相關標籤/搜索