Android中使用JUnit測試
作者:佚名 
  在java開發(fā)中使用junit進行單元測試是常有的事,那么android中呢?答案是肯定的,也可以!使用方式也非常的簡單,只需要在AndroidManifest.xml幾加入兩行配置,然后寫個一類繼承AndroidTestCase類即可,其它的跟java使用junit是一樣的。
 在java開發(fā)中使用junit進行單元測試是常有的事,那么android中呢?答案是肯定的,也可以!
使用方式也非常的簡單,只需要在AndroidManifest.xml幾加入兩行配置,然后寫個一類繼承AndroidTestCase類即可,其它的跟java使用junit是一樣的。
AndroidManifest.xml示例代碼:
- <?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>
 
單元測試類示例代碼:
- 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,創(chuàng)建文件并寫入字符串
 - */
 - 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();
 - }
 - }
 - }
 
責任編輯:徐川 
                    來源:
                    OSChina
 














 
 
 




 
 
 
 