创建的包目录:
创建一个PersonService类,里面只有一个save()方法。
package com.yunfeng.service;
public class PersonService {
public void save(){
String str = "123";
Integer integer = new Integer(str);
}
}
创建一个PersonServiceTest类,里面只有一个testSave()方法。(其中要继承AndroidTestCase)
package com.yunfeng.test;
import com.yunfeng.service.PersonService;
import android.test.AndroidTestCase;
public class PersonServiceTest extends AndroidTestCase {
public void testSave() throws Throwable{
PersonService personService = new PersonService();
personService.save();
}
}
在Xml文件里面添加配置代码(红色字体为添加的代码)
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.yunfeng.junit"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<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="com.yunfeng.junit.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>
<!-- 声明Android框架和目标测试包-->
<instrumentation
android:name="android.test.InstrumentationTestRunner"
android:targetPackage="com.yunfeng.junit">
</instrumentation>
</manifest>
运行Junit的步骤:
1、打开视图:window ---> show View --->Outline
2、显示如下:
3、右键点击“testSave()” --->run as ---> Android Junit Test
4、测试通过显示绿条,如下图: