android中使用junit測試

在java開發中使用junit進行單元測試是常有的事,那麼android中呢?答案是確定的,也能夠! 
使用方式也很是的簡單,只須要在AndroidManifest.xml幾加入兩行配置,而後寫個一類繼承AndroidTestCase類便可.其它的跟java使用junit是同樣的. 

AndroidManifest.xml示例代碼  java

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.javake.hzy.filesave"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="8" />
    <!-- junit測試配置關鍵配置第一處 -->
	<instrumentation android:name="android.test.InstrumentationTestRunner" 
		android:targetPackage="com.javake.hzy.filesave" android:label="my app test"/>
    <application android:icon="@drawable/icon" android:label="@string/app_name">
    	<!-- junit測試配置關鍵配置第二處 -->
    	<uses-library android:name="android.test.runner" />
        <activity android:name=".FileSave"
                  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>

單元測試類示例代碼  android

package com.javake.hzy.filesave;
import java.io.FileOutputStream;
import android.content.Context;
import android.test.AndroidTestCase;

/**
 * 測試類用於測試文件讀寫相關操做
 * 單元測試只須要繼承AndroidTestCase類
 * 測試方法前用test作爲前綴便可
 * 測試時右鍵run as彈出菜單中選擇Android JUnit Test
 * @author hzy
 *
 */
public class MyTest extends AndroidTestCase {
	/**
	 * 測試方法1,建立文件並寫入字符串
	 */
	public void test01() {
		Context context = this.getContext();
		System.out.println(context);
		try {
			FileOutputStream out = context.openFileOutput("hello.txt", Context.MODE_PRIVATE);
			out.write("hello world my name is hzy".getBytes());
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
相關文章
相關標籤/搜索