在单元测试的时候,是先读取清单配置文件AndroidManifest.xml。然后利用反射实例化测试对象,然后调用测试对应的测试方法进行运行
可以重写setUp()方法,这个方法是每个测试方法之前运行的方法。这样可以抽取一些共用的代码放在setUp里面
1、工程结构
2、配置清单文件
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="cn.huangjie.junittest"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:label="@string/app_name"
android:name=".JunittestActivity" >
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- 加上这行相当于引入包的意思 -->
<uses-library android:name="android.test.runner" />
</application>
<instrumentation android:name="android.test.InstrumentationTestRunner"
android:targetPackage="cn.huangjie.junittest" android:label="Tests for My App" />
<!-- 上面targetPackage指定的包要和应用的package相同 -->
</manifest>
3、模拟的service类
package cn.huangjie.service;
public class PersonService{
public void save(String username){
String sub = username.substring(5);
}
public int add(int a, int b){
return a + b;
}
}
4、模拟进行调用
package cn.huangjie.junitservice;
import junit.framework.Assert;
import android.test.AndroidTestCase;
import cn.huangjie.service.PersonService;
public class PersonServiceTest extends AndroidTestCase {
public void testSave(){
PersonService personService = new PersonService();
personService.save(null);
}
public void testAdd(){
PersonService personService = new PersonService();
Assert.assertEquals(personService.add(3, 4), 7);
}
}
5、打印测试结果的几种方法
package cn.huangjie.junitservice;
import android.test.AndroidTestCase;
import android.util.Log;
public class LogTest extends AndroidTestCase{
private static final String TAG = "LogTest";
public void test1(){
Log.i(TAG, "test1");//输出info级别的信息
}
public void test2(){
//默认输出的是info级别的信息,且默认tag是System.out
//并且不会在Console中打印
System.out.println("test2");
}
public void test3(){
//默认输出的是warn级别的信息,且默认tag是System.err
//并且不会在Console中打印
System.err.println("test3");
}
}
test1的输出结果:
test2的输出结果:
test3的输出结果:
工程下载路径:http://download.youkuaiyun.com/detail/wxwzy738/6252365