在实际开发中,开发android软件的过程需要不断地进行测试。而使用Junit测试框架,侧是正规Android开发的必用技术,在Junit中可以得到组件,可以模拟发送事件和检测程序处理的正确性。
权限:
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.sqliteexcercise.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>
<uses-library android:name="android.test.runner"/>
</application>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<instrumentation android:name="android.test.InstrumentationTestRunner"
android:targetPackage="com.example.sqliteexcercise" android:label="Tests for MyApp"/>
第二步:编写单元测试代码(选择要测试的方法,右键点击“Run As”--“Android Junit Test” ):
package cn.itcast.service;
publicclass PersonService{
publicvoid save(String username){
String sub = username.substring(6);
}
publicint add(int a, int b){
return a+b;
}
}
PersonServiceTest
package cn.itcast.junit;
import junit.framework.Assert;
import cn.itcast.service.PersonService;
import android.test.AndroidTestCase;
public class PersonServiceTest extendsAndroidTestCase {
publicvoid testSave() throws Exception{
PersonServiceservice = new PersonService();
service.save(null);
}
publicvoid testAdd() throws Exception{
PersonServiceservice = new PersonService();
intactual = service.add(1, 2);
Assert.assertEquals(3,actual);
}
}
查看与输出日志信息
publicclass LogTest extends AndroidTestCase {
privatestaticfinal String TAG = "LogTest";
publicvoid testOutLog() throws Throwable{
Log.i(TAG, "www.itcast.cn");
}
publicvoid testOutLog5() throws Throwable{
Log.i(TAG, "点点滴滴");
}
publicvoid testOutLog2() throws Throwable{
System.out.println("www.csdn.cn");
}
publicvoid testOutLog3()throws Throwable{
System.err.println("www.sohu.cn");
}
}