Android菜鸟学习笔记

导航

 

对应用进行单元测试步骤:

1,在清单文件AndroidManifest.xml中加入下面品红色代码:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="im.qvod.junitest"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="4"
        android:targetSdkVersion="9" />

    <instrumentation
        android:name="android.test.InstrumentationTestRunner"
        android:label="Tests for My App"
        android:targetPackage="im.qvod.junitest" >
    </instrumentation>

    <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="im.qvod.junitest.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>

注意:

<uses-library android:name="android.test.runner" />的位置,在application里  

<instrumentation
android:name="android.test.InstrumentationTestRunner"
android:label="Tests for My App"
android:targetPackage="im.qvod.junitest" >
</instrumentation>

android:targetPackage="im.qvod.junitest" 是要测试的包名

 

2,编写单元测试用例:

注:单元测试类名 根据你要测试的类命名;继承AndroidTestCase

代码:

需要测试的类:PersonService.java:

package im.qvod.service;

public class PersonService {
    public void save(String username) {
        String sub = username.substring(6);
    }

    public int add(int a, int b) {
        return a + b;
    }

}

单元测试类:PersonServiceTest.java:

package im.qvod.junitest;

import junit.framework.Assert;
import im.qvod.service.PersonService;
import android.test.AndroidTestCase;

public class PersonServiceTest extends AndroidTestCase {
    public void testSave() throws Exception {
        PersonService personService = new PersonService();
        personService.save(null);
    }

    public void testAdd() throws Exception {
        PersonService personService = new PersonService();
        int actual = personService.add(1, 2);
        Assert.assertEquals(3, actual);// 判断实际结果和期望结果

    }

}

 

 

单元测试除了上面应用于需要测试的项目内部外,还可以单独创建出来! 步骤如下图:

 

 

 

posted on 2013-04-03 15:50  Android菜鸟学习笔记  阅读(171)  评论(0)    收藏  举报