10_對應用進行單元測試
-----------------------------------------
1.在實際開發中,開發android軟件的過程需要不斷地進行測試。而使用Junit測試框架,側
是正規的Android開發的必用技術,在Junit中可以得到組件,可以模擬發送事件和檢測程
序處理的正確性。
第一步:首先在AndroidManifest.xml中加入下面紅色代碼:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="cn.itcast.action“ android:versionCode="1“
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<uses-library android:name="android.test.runner" />
....
</application>
<uses-sdk android:minSdkVersion="6" />
<instrumentation android:name="android.test.InstrumentationTestRunner"
android:targetPackage="cn.itcast.action" android:label="Tests for My App" />
</manifest>
-----------------------------------------------------------------
2.第二步:編寫單元測試代碼(選擇要測試的方法,右鍵點擊“Run As”--“Android Junit
Test"):
com.credream.junit
PersonServiceTest.java
package com.credream.junit;
import junit.framework.Assert;
import com.credream.service.PersonServices;
import android.test.AndroidTestCase;
public class PersonServiceTest extends AndroidTestCase
{
public void testSave() throws Exception{//這個方法出錯了
//會拋出一個異常給了測試框架
PersonServices services=new PersonServices();
services.save(null);
}
public void testAdd()throws Exception{
PersonServices services=new PersonServices();
int result=services.add(1, 2);
Assert.assertEquals(3, result);
}
}
----------------------------------------------------------------
com.credream.junitest
JunitestActivity.java
package com.credream.junitest;
import android.app.Activity;
import android.os.Bundle;
public class JunitestActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
-----------------------------------------------------------
com.credream.service
PersonServices.java
package com.credream.service;
import android.text.LoginFilter.UsernameFilterGeneric;
public class PersonServices
{ www.2cto.com
public void save(String username){
String sub=username.substring(6);
}
public int add(int a,int b)
{
return a+b;
}
}
選擇要測試的方法,右鍵點擊“Run As”--“Android Junit Test”
------------------------------------------------------------
2.測試也可以單獨的建一個項目以後通用
新建-->other--> Android Test Project-->
創建一個測試項目