本来以为在android上实现单元测试,应该是很简单的一件事,结果还是花费了一些功夫,主要是在配置文件,和测试环境上花费了不少时间,比想像中要复杂一些,不过也没什么高深的东西,下面简单讲一下。
第一步:新建一个TestCase,记得要继承AndroidTestCase,才能有getContext()来获取当前的上下文变量,这在android测试中很重要的,因为很多的android api都需要context。
public class TestMath extends AndroidTestCase {private int i1;private int i2;    static final String LOG_TAG = "MathTest";    @Overrideprotected void setUp() throws Exception {i1 = 2;        i2 = 3;}public void testAdd() {        assertTrue("testAdd failed", ((i1 + i2) == 5));    }public void testDec() {        assertTrue("testDec failed", ((i2 - i1) == 1));    }@Overrideprotected void tearDown() throws Exception {super.tearDown();}@Overridepublic void testAndroidTestCaseSetupProperly() {super.testAndroidTestCaseSetupProperly();//Log.d( LOG_TAG, "testAndroidTestCaseSetupProperly" );}}

第二步:新建一个TestSuit,这个就继承Junit的TestSuite就可以了,注意这里是用的addTestSuite方法,一开始使用addTest方法就是不能成功。
public class ExampleSuite extends TestSuite {public ExampleSuite() {addTestSuite(TestMath.class);}}

第三步:新建一个Activity,用来启动单元测试,并显示测试结果。系统的AndroidTestRunner竟然什么连个UI界面也没有实现,这里只是最简单的实现了一个
public class TestActivity extends Activity {private TextView resultView;private TextView barView;private TextView messageView;private Thread testRunnerThread;private static final int SHOW_RESULT = 0;private static final int ERROR_FIND = 1;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);resultView = (TextView)findViewById(R.id.ResultView);barView = (TextView)findViewById(R.id.BarView);messageView = (TextView)findViewById(R.id.MessageView);Button lunch = (Button)findViewById(R.id.LunchButton);lunch.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {startTest();}});}private void showMessage(String message) {hander.sendMessage(hander.obtainMessage(ERROR_FIND, message));}private void showResult(String text) {hander.sendMessage(hander.obtainMessage(SHOW_RESULT, text));}private synchronized void startTest() {if (testRunnerThread != null&& testRunnerThread.isAlive()) {testRunnerThread = null;}if (testRunnerThread == null) {testRunnerThread = new Thread(new TestRunner(this));testRunnerThread.start();} else {Toast.makeText(this, "Test is still running", Toast.LENGTH_SHORT).show();}}public Handler hander = new Handler() {public void handleMessage(Message msg) {switch (msg.what) {case SHOW_RESULT:resultView.setText(msg.obj.toString());break;case ERROR_FIND:messageView.append(msg.obj.toString());barView.setBackgroundColor(Color.RED);break;default:break;}}};class TestRunner implements Runnable, TestListener {private Activity parentActivity;private int testCount;private int errorCount;private int failureCount;public TestRunner(Activity parentActivity) {this.parentActivity = parentActivity;}@Overridepublic void run() {testCount = 0;errorCount = 0;failureCount = 0;ExampleSuite suite = new ExampleSuite();AndroidTestRunner testRunner = new AndroidTestRunner();testRunner.setTest(suite);testRunner.addTestListener(this);testRunner.setContext(parentActivity);testRunner.runTest();}@Overridepublic void addError(Test test, Throwable t) {errorCount++;showMessage(t.getMessage() + "\n");}@Overridepublic void addFailure(Test test, AssertionFailedError t) {failureCount++;showMessage(t.getMessage() + "\n");}@Overridepublic void endTest(Test test) {showResult(getResult());}@Overridepublic void startTest(Test test) {testCount++;}private String getResult() {int successCount = testCount - failureCount - errorCount;return "Test:" + testCount + " Success:" + successCount + " Failed:" + failureCount + " Error:" + errorCount;}}}

第四步:修改AndroidManifest.xml,加入<uses-library android:name="android.test.runner" />,不然会提示找不到AndroidTestRunner,这里需要注意是这句话是放在applications下面的,我一开始也不知道,放错了地方,浪费了不少时间
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"      package="com.test.sample"      android:versionCode="1"      android:versionName="1.0">    <application android:icon="@drawable/icon" android:label="@string/app_name" android:debuggable="true">        <activity android:name=".TestActivity"                  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>    <uses-sdk android:minSdkVersion="4" /></manifest> 

更多相关文章

  1. Android异步处理常用方法
  2. Android设置TextView显示指定个数字符,超过部分显示...(省略号)的
  3. Android中如何使用JUnit进行单元测试
  4. Android使用自定义字体的方法
  5. Android 环信官方Demo3.3.2详细配置方法
  6. Android中经常用到的方法--SDcard下文件的操作
  7. Android Intent调用方法总结
  8. App测试中ios和Android的区别

随机推荐

  1. Android自定义视图二:如何绘制内容
  2. [android] 将Java程序移植到android上
  3. Android之内存缓存——LruCache的使用及
  4. Android TextView的特殊使用:阴影,加样式
  5. Handler的运行机制
  6. Android(安卓)zip文件中读取图片实现Gall
  7. Android 4.0 input touch解析(一)
  8. android自定义布局中的平滑移动
  9. Java讲师与Android讲师通缉令--悬赏2000
  10. Android 开发者必备的十个工具