Android之单元测试——下
16lz
2021-01-26
在项目中实际遇到的问题,和大家做一个分享.
#1.在控件的模拟事件执行的时候,尽量不要使用@UiThreadTest.因为如果一个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.怎样对一个Service进行测试。
/** * 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.我在项目中写的Database测试类也贴出来给大家看看
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 + "<<<<<"); } System.out.println("@@@" +"iterator method is ending......" + "@@@"); } public void testGetProblemDetailByIdAllData() { for(ProblemVO pd: problemDataSet) { String problemId = pd.getId() + ""; String problemName = pd.getProblemName(); ProblemDetailVO pdvo = testSQLiteHelper.getProblemDetailById(problemId, problemName); System.out.println(">>>>>" + pdvo + "<<<<<"); } } //test the data count ---> 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(); } }
更多相关文章
- Android(安卓)高级控件(一)
- 【Android】Intent传递数据量过大的问题android.os.TransactionT
- Android(安卓)Service中给其他的组件回传数据。
- Android中关于数据库SQLite的insert插入操作的理解
- GitHub 上受欢迎的 Android(安卓)UI Library 整理二
- android inflate初探
- android 自定义ViewAnimator文字轮播广告控件——自定义控件学习
- Android的用GreenDao操作数据库
- SQLite数据库增删改查操作