我添加此項,因爲我認爲它可以幫助想要測試其內容提供者的程序員。
想象一下你的Content Provider被稱爲MyProvider,並且你有一個名爲MyProviderContract的契約類定義了一些常量。
首先,您將編寫一個名爲MyProviderTestCase
的測試類,它繼承自ProviderTestCase2<MyProvider>
。你必須定義一個構造函數,將調用super
構造:
public MyProviderTestCase() {
super(MyProvider.class, MyProviderContract.AUTHORITY);
}
然後,而不是直接使用您的供應商(避免使用getProvider()
作爲內容提供商的用戶將不能直接訪問它),使用getMockContentResolver()
以獲得對內容解析器的引用,然後調用此內容解析器的方法(query
,insert
等)。在下面的代碼中,我展示瞭如何測試insert
方法。
public void testInsert() {
Uri uri = MyProviderContract.CONTENT_URI;
ContentValues values = new ContentValues();
values.put(MyProviderContract.FIELD1, "value 1");
values.put(MyProviderContract.FIELD2, "value 2");
Uri resultingUri = getMockContentResolver().insert(uri, values);
// Then you can test the correct execution of your insert:
assertNotNull(resultingUri);
long id = ContentUris.parseId(resultingUri);
assertTrue(id > 0);
}
然後,只要你想,你可以添加儘可能多的測試方法,使用內容解析,而不是直接在內容提供商,因爲會做你的內容提供商的用戶。
互聯網上的ProviderTestCase2類沒有太多示例代碼。這非常有幫助。 – zzzzzzzzzzzzzzzzzzzzzzzzzzzzzz 2012-07-06 04:51:04
在[Android文檔](http://developer.android.com/tools/testing/contentprovider_testing.html#WhatToTest)中,他們建議不要直接使用您的內容提供程序,而要通過內容解析程序。請閱讀我的帖子,以查看如何測試內容提供者的更充分示例。 – eternay 2013-03-06 13:31:19