资料原文链接:http://www.uml.org.cn/Test/200912177.asp
1.项目目录如下:
2.项目代码:
xml文件AndroidManifest.xml配置如下:
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.testapp" android:versionCode="1" android:versionName="1.0"> <application android:icon="@drawable/icon" android:label="@string/app_name"> <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> <uses-library android:name="android.test.runner" /> </application> <instrumentation android:name="android.test.InstrumentationTestRunner" android:targetPackage="com.testapp" android:label="Test for my app" /></manifest>
MainActivity类的内容如下:
package com.testapp;import android.app.Activity;import android.os.Bundle;public class MainActivity extends Activity{ /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } /** * 求a+b * * @param a * @param b * @return */ public int sum(int a, int b) { return a + b; } /** * 求a-b * * @param a * @param b * @return */ public int substract(int a, int b) { return a - b; }}
测试类TestMainActivity的代码如下:
package test.com.testapp;import com.testapp.MainActivity;import android.app.Activity;import android.test.ActivityInstrumentationTestCase;import android.test.suitebuilder.annotation.MediumTest;public class TestMainActivity extends ActivityInstrumentationTestCase<MainActivity>{ public TestMainActivity() { super("com.testapp", MainActivity.class); } /** * @param pkg * @param activityClass */ public TestMainActivity(String pkg, Class<MainActivity> activityClass) { super(pkg, activityClass); // TODO Auto-generated constructor stub } @MediumTest public void testSum() { assertEquals(3, getActivity().sum(1, 2)); } @MediumTest public void testSubstract() { assertEquals(-1, getActivity().substract(1, 2)); }}
3.项目运行设置:
在命令窗口输入如下:adb shell pm list packages
最后输入:adb shell am instrument -e class test.com.testapp.TestMainActivity -w com.testapp/android.test.InstrumentationTestRun
ner
结果就出来了
正确结果:
错误结果:
一篇不错文章:http://tech.it168.com/a2010/1027/1118/000001118903_all.shtml