如何在安卓开发中单元测试

在JavaEE中,有一个Junit测试包

而在开发安卓中,我们要使用谷歌公司开发好的一些类

代码如下:

这里要测试一个计算器类:

package org.dreamtech.helloworld;

public class Calc {
    // 计算器类

    public int add(int x, int y) {
        return x + y;
    }
}

在配置文件下添加这一行:

 <application
        android:allowBackup="true"
        android:enabled="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="org.dreamtech.helloworld.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:name="android.test.InstrumentationTestRunner"
        android:targetPackage="org.dreamtech.helloworld" />

写一个测试类:

package org.dreamtech.helloworld;

import android.test.AndroidTestCase;

public class Test extends AndroidTestCase {
    public void testAdd() {
        Calc calc = new Calc();
        int result = calc.add(3, 5);
        // 断言:第一个参数是期望值
        assertEquals(8, result);
    }
}

测试成功!

猜你喜欢

转载自www.cnblogs.com/xuyiqing/p/8858310.html