Androidのユニットテスト
19178 ワード
プロジェクトで実際に出会った問題は、みんなと共有します.
#1.コントロールのシミュレーションイベント実行時に@UiThreadTestを使用しないようにする.1つのActivityでコントロールが多いとUIスレッドがブロックするやすいためである.
代わりに、次のコードを使用できます.
#2.コントロールをどのように圧力テストするか、私の処理はViewのClickイベントを呼び出し続けることです.
#3.コントロールに表示するフィールドのテストで、表示するフィールドはstringsから来ている.xml
#4.Activityで各Buttonの圧力テストをどのように行い、スレッドの制御に注意するか
#5.tearDown()メソッドで一般的に行われる操作.
#6.appが走る前に、すべてのwidgetが空にならないことを保証します.
#7.サービスをテストする方法.
#8.androidのデータベースをユニットテストする方法.ここでは、ネット上のケースを参照します.
データベースの論理コードは次のとおりです.
#9.私がプロジェクトに書いたデータベーステストクラスも貼って見せます
#1.コントロールのシミュレーションイベント実行時に@UiThreadTestを使用しないようにする.1つのActivityでコントロールが多いとUIスレッドがブロックするやすいためである.
代わりに、次のコードを使用できます.
private class PerformClick implements Runnable {
Button hhButton;
public PerformClick(Button HHButton) {
hhButton = HHButton;
}
@Override
public void run() {
hhButton.performClick();
}
}
#2.コントロールをどのように圧力テストするか、私の処理はViewのClickイベントを呼び出し続けることです.
public void stressTestForButton(final Button btn,int pressNumber) {
for(int i = 0;i <= pressNumber;i++) {
new Thread(new Runnable() {
@Override
public void run() {
btn.requestFocus();
btn.performClick();
btn.clearFocus();
}
});
Log.i("count times", i + "");
}
}
#3.コントロールに表示するフィールドのテストで、表示するフィールドはstringsから来ている.xml
public void testText() {
//testing String values
assertEquals(hayhouseLinkButtonString, (String)hayhouseLinkButton.getText());
assertEquals(hayhouseradioLinkButtonString, (String)hayhouseradioLinkButton.getText());
assertEquals(healLinkButtonString, (String)healLinkButton.getText());
}
#4.Activityで各Buttonの圧力テストをどのように行い、スレッドの制御に注意するか
public void testButtonStress() {
Log.v(TAG, "testButtonStress method is starting");
SystemClock.sleep(400);
new OperateUtil().new performButtonClickStress(hayhouseLinkButton,10);
SystemClock.sleep(400);
addClickTimes(hayhouseLinkButton,50);
SystemClock.sleep(400);
addClickTimes(hayhouseLinkButton,100);
SystemClock.sleep(400);
addClickTimes(hayhouseLinkButton,200);
SystemClock.sleep(400);
new OperateUtil().new performButtonClickStress(hayhouseradioLinkButton,10);
SystemClock.sleep(400);
addClickTimes(hayhouseradioLinkButton,50);
SystemClock.sleep(400);
addClickTimes(hayhouseradioLinkButton,100);
SystemClock.sleep(400);
addClickTimes(hayhouseradioLinkButton,200);
SystemClock.sleep(400);
new OperateUtil().new performButtonClickStress(healLinkButton,10);
SystemClock.sleep(400);
addClickTimes(healLinkButton,50);
SystemClock.sleep(400);
addClickTimes(healLinkButton,100);
SystemClock.sleep(400);
addClickTimes(healLinkButton,200);
}
#5.tearDown()メソッドで一般的に行われる操作.
@Override
protected void tearDown() throws Exception {
hayhouseLinkButton.clearFocus();
hayhouseLinkButton.clearComposingText();
hayhouseradioLinkButton.clearFocus();
hayhouseradioLinkButton.clearComposingText();
healLinkButton.clearFocus();
healLinkButton.clearComposingText();
detailView.clearFocus();
hayHouseActivity.finish();
super.tearDown();
}
#6.appが走る前に、すべてのwidgetが空にならないことを保証します.
public void testPreConditions() {
assertTrue(hayhouseLinkButton != null);
assertTrue(hayhouseradioLinkButton != null);
assertTrue(healLinkButton != null);
assertTrue(gobackButton_hayhouse != null);
assertTrue(detailView != null);
}
#7.サービスをテストする方法.
/**
* From sdk description
*
* This test case provides a framework in which you can test Service classes
* in a controlled environment. It provides basic support for the lifecycle of a
* Service, and hooks with which you can inject various dependencies and
* control the environment in which your Service is tested.
*/
public class AudioServiceTest extends ServiceTestCase {
private static final String TAG = "-----AudioServiceTest-----";
public AudioServiceTest() {
super(AudioService.class);
}
@Override
protected void setUp() throws Exception {
Log.i(TAG, "=====AudioServiceTest setUp Start=====");
super.setUp();
Log.i(TAG, "=====AudioServiceTest setUp End=====");
}
/**
* 2011.09.16 jack.li add......
* test basic startup/shutdown of Service
*/
@SmallTest
public void testStartable() {
Log.i(TAG, "+++++AudioServiceTest testStartable Start+++++");
Intent startIntent = new Intent();
startIntent.setClass(getContext(), AudioService.class);
startService(startIntent);
assertNotNull(getService());
}
/**
* 2011.09.16 jack.li add......
* test binding to service
*/
@MediumTest
public void testBindable() {
Log.i(TAG, "+++++AudioServiceTest testBindable Start+++++");
Intent startIntent = new Intent();
startIntent.setClass(getContext(), AudioService.class);
IBinder service = bindService(startIntent);
assertNotNull(service);
}
}
#8.androidのデータベースをユニットテストする方法.ここでは、ネット上のケースを参照します.
データベースの論理コードは次のとおりです.
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import com.android.hanhan.R;
public class DatabaseService {
private DatabaseHelper dbOpenHelper;
protected static final String TBL_NAME = "article";
protected static final String FIELD_ID = "id";
protected static final String FIELD_TITLE = "title";
protected static final String FIELD_CONTENT = "content";
protected static final String FIELD_DELETE = "deleted";
protected static final String FIELD_PUBLISHDATE = "publishdate";
protected static final String FIELD_FAVORITE = "favorite";
protected static final String FIELD_CLICKCOUNT = "clickcount";
protected static final String FIELD_FAVORITEDATE = "favoritedate";
// ,
public DatabaseService(Context context) {
dbOpenHelper = new DatabaseHelper(context);
}
//
public void dropTable(String taleName) {
dbOpenHelper.getWritableDatabase().execSQL(
"DROP TABLE IF EXISTS " + taleName);
}
//
public void closeDB() {
dbOpenHelper.getWritableDatabase().close();
}
// TBL_NAME
public List
このsqliteデータベース・ユニットをテストする方法は、次のとおりです.import android.test.AndroidTestCase;
import com.android.hanhan.util.DatabaseService;
public class DatabaseServiceTest extends AndroidTestCase{
private DatabaseService dbs;
@Override
protected void setUp() throws Exception {
dbs = new DatabaseService(getContext());
}
@Override
protected void tearDown() throws Exception {
dbs.closeDB();
}
public void testPageCount() throws Exception{
assertEquals(12, dbs.getPageCount());
}
public void testFetchALLArticle() throws Exception{
assertEquals(12, dbs.fetchALLArticle().size());
}
}
#9.私がプロジェクトに書いたデータベーステストクラスも貼って見せます
package com.ceosoftcenters.healyourbody.db.test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import com.ceosoftcenters.healyourbody.sqlite.SQLiteHelper;
import com.ceosoftcenters.healyourbody.sqlite.vo.ProblemDetailVO;
import com.ceosoftcenters.healyourbody.sqlite.vo.ProblemVO;
import com.ceosoftcenters.healyourbody.util.ConstantsUtil;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.test.AndroidTestCase;
import android.util.Log;
/**
* @file SQLiteHelperTest.java
* @author Jack.Li
* @date 2011.09.15
* @description this class is mainly for SQLite Database's unit testing
* AndroidTestCase--->Extend this if you need to access Resources or other things that depend on Activity Context.
*
*/
public class SQLiteHelperTest extends AndroidTestCase {
private static final String TAG = "-----SQLiteHelperTest-----";
//declare SQLiteHelper's instance ---> testSQLiteHelper
private SQLiteHelper testSQLiteHelper;
//private HealYourBodyApplication hybApp;
//declare SQLiteDatabase's instance ---> database
SQLiteDatabase database;
//all the data from the database
private ArrayList problemDataSet = null;
//2011.09.26 jack add......custom data for testing
private List> list_testSQLiteHelper = null;
public static final String ITEM_PROBLEM_ID= "problem_Id";
public static final String ITEM_PROBLEM_NAME = "problem_Name";
//2011.10.12.PM jack new add...
public int ITEM_Number;
@Override
protected void setUp() {
try {
super.setUp();
}catch (Exception e) {
e.printStackTrace();
}
Log.i(TAG, "==SQLiteHelperTest setUp method is starting==");
testSQLiteHelper = new SQLiteHelper(getContext());
System.out.println("+++++" + testSQLiteHelper + "+++++");
database = SQLiteDatabase.openOrCreateDatabase(getContext().getFilesDir().getAbsolutePath() + ConstantsUtil.HEAL_YOUR_BODY_DBFILE_PATH, null);
System.out.println("+++++" + database + "+++++");
list_testSQLiteHelper = new ArrayList>();
getListValue(list_testSQLiteHelper);
problemDataSet = new ArrayList();
setProblemDataSet(problemDataSet);
Log.i(TAG, "==SQLiteHelperTest setUp method is ending==");
}
//set values for problemDataSet
public void setProblemDataSet(ArrayList problemDataSet) {
//query database file to set data for list view
SQLiteDatabase database = SQLiteDatabase.openOrCreateDatabase(getContext().getFilesDir().getAbsolutePath() + ConstantsUtil.HEAL_YOUR_BODY_DBFILE_PATH, null);
//query all data from the table bookdata -----> String sql = "select id,problem from bookdata";
Cursor cursor = database.rawQuery(ConstantsUtil.QUERY_ALL_ITEMS_ID_PROBLEM_SQL,null);
if (cursor.getCount() > 0) {
cursor.moveToFirst();
ProblemVO pd = null;
while(!cursor.isLast()) {
int id = cursor.getInt(0);
String problemName = cursor.getString(1);
pd = new ProblemVO(id,problemName);
problemDataSet.add(pd);
cursor.moveToNext();
}
int id = cursor.getInt(0);
String problemName = cursor.getString(1);
pd = new ProblemVO(id,problemName);
problemDataSet.add(pd);
//get the problemDtaSet's size -----> because it is a manually edit database,some items do not be used.
//So the last id number is not the problemDataSet's size
//get the problemDataSet's size
System.out.println("**********" + problemDataSet.size() + "**********");
ITEM_Number = problemDataSet.size();
}
cursor.close();
database.close();
}
//custom list values for testing
public void getListValue(List> list_testSQLiteHelper) {
//I don't know why the last item is -----> "Itis" -----> solved
//we think "Itis" is a dirty data
//the custom data's number are 20
list_testSQLiteHelper.add(SQLiteHelperTest.getHashMapValue("5", "Acne"));
list_testSQLiteHelper.add(SQLiteHelperTest.getHashMapValue("11", "Aids"));
list_testSQLiteHelper.add(SQLiteHelperTest.getHashMapValue("16", "Amnesia"));
list_testSQLiteHelper.add(SQLiteHelperTest.getHashMapValue("22", "Anus"));
list_testSQLiteHelper.add(SQLiteHelperTest.getHashMapValue("48", "Bad Breath"));
list_testSQLiteHelper.add(SQLiteHelperTest.getHashMapValue("54", "Birth"));
list_testSQLiteHelper.add(SQLiteHelperTest.getHashMapValue("64", "Blood"));
list_testSQLiteHelper.add(SQLiteHelperTest.getHashMapValue("80", "Brain"));
list_testSQLiteHelper.add(SQLiteHelperTest.getHashMapValue("117", "Coma"));
list_testSQLiteHelper.add(SQLiteHelperTest.getHashMapValue("134", "Death"));
list_testSQLiteHelper.add(SQLiteHelperTest.getHashMapValue("169", "Fat"));
list_testSQLiteHelper.add(SQLiteHelperTest.getHashMapValue("177", "Fever"));
list_testSQLiteHelper.add(SQLiteHelperTest.getHashMapValue("186", "Fistula"));
list_testSQLiteHelper.add(SQLiteHelperTest.getHashMapValue("198", "Gastritis"));
list_testSQLiteHelper.add(SQLiteHelperTest.getHashMapValue("234", "Hypertension"));
list_testSQLiteHelper.add(SQLiteHelperTest.getHashMapValue("252", "Itching"));
list_testSQLiteHelper.add(SQLiteHelperTest.getHashMapValue("260", "Knee"));
list_testSQLiteHelper.add(SQLiteHelperTest.getHashMapValue("331", "Petit Mal"));
list_testSQLiteHelper.add(SQLiteHelperTest.getHashMapValue("364", "Root Canal"));
list_testSQLiteHelper.add(SQLiteHelperTest.getHashMapValue("444", "Wrist"));
}
//jack new add...2011.09.26.am
public static HashMap getHashMapValue(String problem_Id,String problem_Name) {
HashMap hm_testSQLiteHelper = new HashMap();
hm_testSQLiteHelper.put(ITEM_PROBLEM_ID, problem_Id);
hm_testSQLiteHelper.put(ITEM_PROBLEM_NAME, problem_Name);
return hm_testSQLiteHelper;
}
public void testGetProblemDetailById() {
//total item's number is 440 -----> get the size 2011.10.08.am
//iterator the list_testSQLiteHelper,to get per item's id and name
Iterator> it = list_testSQLiteHelper.iterator();
while(it.hasNext()) {
Map hm = it.next();
String problem_Id = (String)hm.get(ITEM_PROBLEM_ID);
String Problem_Name = (String)hm.get(ITEM_PROBLEM_NAME);
ProblemDetailVO pdvo = testSQLiteHelper.getProblemDetailById(problem_Id, Problem_Name);
//perform toString() method
System.out.println(">>>>>" + pdvo + "<<<<>>>>" + pdvo + "<<<< sum
public void testSetProblemDataSetSize() throws Exception{
//put all the ProblemVO instance into the problemDataSet ArrayList
//problemDataSet = new HealYourBodyApplication().getProblemDataSet();
assertEquals(440, problemDataSet.size());
assertEquals(false, problemDataSet.size() == 445);
assertEquals(false, problemDataSet.size() == 335);
}
@Override
protected void tearDown() throws Exception {
Log.i(TAG, "==SQLiteHelperTest tearDown method is starting==");
//close the resource
database.close();
super.tearDown();
}
}