源码下载(免下载积分):下载
Content Provider 用在应用程序间的数据的存储和检索,这个是对如何利用android的测试包来对Content Provider进行测试。
测试Content Provider的测试用例类是 ProviderTestCase2,这个类可以使得content
provider处于孤立的环境中,利用Mock类(例如IsolatedContext
and MockContentResolver)来测试。和其它测试一样,provider的测试包也运行在InstrumentationTestRunner的控制之下
Content
Provider测试API
ProviderTestCase2: 这个类继承了类,这个最重要的特点是创建孤立的测试环境,
Mock object 类:ProviderTestCase2使用了IsolatedContext
and MockContentResolver,这两个类是标准的mock类
测试案例:
1. 继承
ProviderTestCase2
public class DictionaryProviderTest
extends ProviderTestCase2<DictionaryProveder>{
2. 添加构造函数
private MockContentResolver mResolver;
/*
* 构造函数所做的事情;
* 1. 创建IsolatedContext,用于文件和数据库的操作
* 2. 创建MockContentResolver
* 3. 实例化provider
*/
public DictionaryProviderTest()
{
super(DictionaryProveder.class,DictionaryProveder.AUTHORITY);
// TODO Auto-generated constructor stub
}
3. 添加setUp()方法和先验测试
@Override
protected void setUp() throws Exception {
// TODO Auto-generated method stub
super.setUp();
//获取MockContentResolver对象
mResolver = this.getMockContentResolver();
}
//先验测试
public void testPrecondtions()
{
assertNotNull(mResolver);
}
3. 测试provider的检索
//测试ContentProvider的
public void testContentProviderQuery()
{
Uri uri = Uri.parse
("content://com.example.mydictionary.DictionaryProveder/words/");
String[] projection = {DictionaryOpenHelper.DictionaryEntry.COLUMN_WORD
,DictionaryOpenHelper.DictionaryEntry.COLUMN_DEFINATION};
Cursor cursor = mResolver.query(uri, projection, null, null, null);
assertNotNull(cursor);
cursor.moveToFirst();
if (cursor.moveToNext()) {
assertEquals(2,cursor.getColumnCount());
assertEquals("abbey", cursor.getString(0));
assertEquals("n. a monastery ruled by an abbot", cursor.getString(1));
}
}
}
这个测试可以说是为了测试而测试。
怎么如何规范的测试呢?
参考资料:
http://developer.android.com/tools/testing/contentprovider_testing.html
http://matthewtyler.io/testing-content-providers-android-programming/
ContentProviderTest,布布扣,bubuko.com
原文:http://blog.csdn.net/wangfei199101/article/details/24835839