Android單元測試 Instrumentation


開發中我們需要對部分功能進行單元測試,啓動Activity來測試部分小功能,有點小題大作,殺雞用牛刀。

我們可以用Android單元測試 Instrumentation


本篇只是入門,起到拋磚的效果


Instrumentation無界面,具有啓動能力。

下面通過一個簡單的例子來講解Instrumentation的基本測試方法:


我們測試工程

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="cn.hpc.assistant"
    android:versionCode="1"
    android:versionName="1.0" >


    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="14" />


     <application
        android:name=".FloatApplication"
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" android:debuggable="true">
        <activity
            android:name="cn.hpc.assistant.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>




        <uses-library android:name="android.test.runner" /><!--八股文:  引入測試庫-->
    </application>
<!--  八股文:被測試的目標包與instrumentation的名稱。-->
    <instrumentation
        android:name="android.test.InstrumentationTestRunner"
        android:label="Tests for My App"
        android:targetPackage="cn.hpc.assistant" />


</manifest>

Mainactivity.java

package cn.hpc.assistant;

import android.app.Activity;
import android.content.Context;
import android.graphics.PixelFormat;
import android.graphics.Point;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.TextView;

public class MainActivity extends Activity {
	private TextView tv = null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		tv = (TextView) this.findViewById(R.id.text1);
		this.findViewById(R.id.id_btn_fun).setOnClickListener(mOnClickListener);

	}


	View.OnClickListener mOnClickListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.id_btn_fun:
				fun();
				break;
			default:

			}
		}
	};

	private void fun(){
		tv.setText(android.os.Build.MODEL + android.os.Build.getRadioVersion());
	}

}


佈局文件:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/text1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/hello_world" />

    <Button
        android:id="@+id/id_btn_fun"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/id_btn_day"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" 
        android:text="Day"/>

    <Button
        android:id="@+id/id_btn_night"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Night" />

</LinearLayout>


鍵的測試文件:

package cn.hpc.assistant.test;

import junit.framework.Assert;
import android.content.Intent;
import android.os.SystemClock;
import android.test.InstrumentationTestCase;
import android.widget.Button;
import android.widget.TextView;
import cn.hpc.assistant.MainActivity;
import cn.hpc.assistant.R;

public class TestMyApp extends InstrumentationTestCase {

	MainActivity mActivity = null;
	private Button button = null;

	private TextView text = null;

	public void testSample() throws Throwable {
		Assert.assertTrue(1 + 1 == 3); // 測試一個錯誤的結果
	}

	@Override
	protected void tearDown() throws Exception {
		// TODO Auto-generated method stub
		mActivity.finish();

		super.tearDown();
	}

	@Override
	protected void setUp() throws Exception {
		// TODO Auto-generated method stub
		super.setUp();
		Intent intent = new Intent();

		intent.setClassName("cn.hpc.assistant", MainActivity.class.getName());

		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

		mActivity = (MainActivity) getInstrumentation().startActivitySync(
				intent);

		text = (TextView) mActivity.findViewById(R.id.text1);

		button = (Button) mActivity.findViewById(R.id.id_btn_fun);

	}

	/*
	 * 
	 * 活動功能測試
	 */

	public void testActivity() throws Exception {
		// 測試鍵壯性,連續運行某項功能100次,點擊Button 100次
		for (int i = 0; i < 100; ++i) {
			getInstrumentation().runOnMainSync(new PerformClick(button));
			SystemClock.sleep(500); // 中間間隔 0.5秒
		}
		assertEquals("Android InstrumentationTestCase", text.getText().toString()); //檢查運行後的輸出結果

	}

	/*
	 * 
	 * 模擬按鈕點擊的接口
	 */

	private class PerformClick implements Runnable {

		Button btn;

		public PerformClick(Button button) {
			btn = button;
		}

		public void run() {
			btn.performClick();
		}

	}

}


在android Developer中有如下的解釋

protected void setUp ()
Since: API Level 3
Sets up the fixture, for example, open a network connection. This method is called before a test is executed.

setUp ()用來初始設置,如啓動一個Activity,初始化資源等。

protected void tearDown ()
Since: API Level 3
Make sure all resources are cleaned up and garbage collected before moving on to the next test. Subclasses that override this method should make sure they call super.tearDown() at the end of the overriding method.

tearDown () 用來垃圾清理與資源回收。



這個測試方法中,模擬了一個按鈕點擊事件,檢查程序運行是否預期的結果。

在這裏PerformClick這個方法引入Runnable接口,通過線程來執行模擬事件。這樣的好處,不阻滯UI線程。


用Eclipse集成的JUnit工具啓動測試

在Eclipse中選擇工程Sample,單擊右鍵,在Run as子菜單選項中選擇Android JUnit Test




測試後,顯示測試中的錯誤信息,




完畢,



歡迎轉載,轉載請註明出處。謝謝!

http://blog.csdn.net/hpccn/article/details/8439784

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章