Android有时候我们需要调试或者测试一个类是否正确,我们可以使用如下方法。以下面的程序为例,我们测试下面的Person类是否正确。
package com.heima.junit;
public class Person {
public void eat() {
System.out.println("eat ....");
}
public int divide(int i, int j) {
return i/j;
}
}
我们很容易看出Person类的divide()成员方法的第二个参数不能为0,假设我们不知道。
第一步:写个类去继承 AndroidTestCase 类
package test;
import com.heima.junit.Person;
import android.test.AndroidTestCase;
public class testPerson extends AndroidTestCase {
public void test1() {
Person p = new Person();
p.eat();
System.out.println(p.divide(2, 1));
}
public void test2() {
Person p = new Person();
p.eat();
System.out.println(p.divide(2, 0));
}
}
第二步:清单文件manifest中, 添加instrumentation 指令集
<instrumentation android:name="android.test.InstrumentationTestRunner"
android:targetPackage="com.heima.junit" />
第三步:继续在清单 文件application中,添加 uses-library<uses-library android:name="android.test.runner" />
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.heima.junit.test"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" />
<instrumentation
android:name="android.test.InstrumentationTestRunner"
android:targetPackage="com.heima.junit" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<uses-library android:name="android.test.runner" />
</application>
</manifest>
按以下方法执行: