在Eclipse下进行Android单元测试

随着开发项目的规模越来越大,我们有必要在开发过程中对项目中的核心方法进行单元测试,以更快更好地定位出bug位置并解决问题。

假设笔者在 HttpUtils.java中 定义了一个 doGet(String msg) 的网络请求方法,下面需要在 Eclipse 测试其正确性。

首先创建一个测试类 TestHttpUtils ,使其继承 AndroidTestCase ,为了规范,最好单独建一个测试包如 test

package test;

import utils.HttpUtils;
import android.test.AndroidTestCase;
import android.util.Log;

public class TestHttpUtils extends AndroidTestCase {

    public void testSendInfo() {
        String res = HttpUtils.doGet("给我讲个笑话");
        Log.e("TAG", res);
        res = HttpUtils.doGet("给我讲个鬼故事");
        Log.e("TAG", res);
        res = HttpUtils.doGet("你好");
        Log.e("TAG", res);
        res = HttpUtils.doGet("你真美");
        Log.e("TAG", res);
    }
}

然后打开 AndroidMainfest.xml ,搭建如下测试环境:

application 中添加 <uses-library android:name=”android.test.runner” />

<application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <uses-library android:name="android.test.runner" />

        <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>
</application>

再添加 instrumentation ,注意android:targetPackage要和AndroidMainfest.xml 中的package=”com.example.http” 保持一致

<instrumentation
        android:name="android.test.InstrumentationTestRunner"
        android:label="this is a test"
        android:targetPackage="com.example.http" >
</instrumentation>

最后回到 TestHttpUtils.java,选中方法 testSendInfo(),右键选择 Run as,选择 Android JUnit Test 即可

    原文作者:陆嘉杰
    原文地址: https://www.jianshu.com/p/73cf53d995e6
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞