在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 即可

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容