先前講過Activity Test, Unit Test, Service Test,
此篇來探討如何對Database做自動化測試.
由於Database為Android API 相關的測試, 需將測試檔案放於module-name/src/androidTest/java/ 路徑下.
(請參閱 Android App Test 基本概念)
Step 1: 產生測試檔
利用 Ctrl + Shift + T 建立 MainContentProviderTest.java
並繼承ProviderTestCase2
Step 2: 初始化
傳入要測試的Class檔, 以及Database權限
1 2 3
| public MainContentProviderTest() { super(MainContentProvider.class, MainDbContract.AUTHORITY); }
|
需與AndroidManifest.xml 中宣告的權限一致.
AndroidManifest.xml1 2 3
| <provider android:name=".database.MainContentProvider" android:authorities="com.projects.nick.database" android:exported="false" />
|
Step 3: 建立自動化測試
資料插入測試
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| @SmallTest public void testInsert() { Uri uri = MainDbContract.getWarriorsUri(); ContentValues values = new ContentValues(); values.put(Warriors.COLUMN_NAME, "Thompson"); values.put(Warriors.COLUMN_NUMBER, 11); Uri resultingUri = getMockContentResolver().insert(uri, values); assertNotNull(resultingUri); long id = ContentUris.parseId(resultingUri); assertTrue(id > 0); }
|
刪除資料測試
1 2 3 4 5 6 7 8 9 10 11 12
| @SmallTest public void testDelete() { testInsert();
Uri uri = MainDbContract.getWarriorsUri(); String selection = Warriors.COLUMN_NAME + "=?"; String[] selections = new String[] {"Thompson"}; int count = getMockContentResolver().delete(uri, selection, selections); assertEquals(1, count); }
|
Source Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| public class MainContentProviderTest extends ProviderTestCase2<MainContentProvider> {
public MainContentProviderTest() { super(MainContentProvider.class, MainDbContract.AUTHORITY); }
@Override protected void setUp() throws Exception { super.setUp(); }
@SmallTest public void testInsert() { Uri uri = MainDbContract.getWarriorsUri(); ContentValues values = new ContentValues(); values.put(Warriors.COLUMN_NAME, "Thompson"); values.put(Warriors.COLUMN_NUMBER, 11); Uri resultingUri = getMockContentResolver().insert(uri, values); assertNotNull(resultingUri); long id = ContentUris.parseId(resultingUri); assertTrue(id > 0); }
@SmallTest public void testDelete() { testInsert();
Uri uri = MainDbContract.getWarriorsUri(); String selection = Warriors.COLUMN_NAME + "=?"; String[] selections = new String[] {"Thompson"}; int count = getMockContentResolver().delete(uri, selection, selections); assertEquals(1, count); } @Override protected void tearDown() throws Exception { super.tearDown(); } }
|