Android下的Junit单元测试

Android开发中,单元测试是必不可少的,配置Junit相对简单,步骤如下:


第一步:首先在AndroidManifest.xml中加入下面带注释的代码

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.haier.junit"
    android:versionCode="1"
    android:versionName="1.0" >
	<!-- Junit测试的指令集 -->
    <instrumentation
        android:name="android.test.InstrumentationTestRunner"
        android:targetPackage="com.haier.junit" />

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        
	<!--Junit测试使用的函数库 -->
        <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>

</manifest>

注意:

1)上面targetPackage指定的包要和应用的package相同。
2)如果不在Manifest中做如下配置,控制台会抛出如下异常:Junit does not specify a android.test.InstrumentationTestRunner instrumentation or does not declare uses-library android.test.runner in its AndroidManifest.xml

第二步:编写单元测试代码(执行测试:Outline选择要测试的方法,右键点击“Run As”--“Android Junit Test” ):

import android.test.AndroidTestCase;
import android.util.Log;
public class XMLTest extends AndroidTestCase {
	 public void testSomething() throws Throwable {
		Assert.assertTrue(1 + 1 == 3);
	 }
}

注意:

1)必需把异常抛出去,Junit才能捕获到。

2)AndroidTestCase是对Junit进行了封装,使之能在dalvik上运行。

3Junit测试操作会将代码打包成apk,上传到设备,再运行测试。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

二一点

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值