首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在Robolectric中测试SQLite数据库

在Robolectric中测试SQLite数据库
EN

Stack Overflow用户
提问于 2011-09-06 21:36:28
回答 1查看 15.1K关注 0票数 17

我正尝试在我的Android应用程序中使用Robolectric来测试一个简单的SQLite数据库。我放入了一些值,但当读回它们时,返回0行。

我使用SQLiteOpenHelper类来访问数据库。

代码语言:javascript
复制
// RequestCache extends SQLiteOpenHelper
RequestCache cache = new RequestCache(activity); 
SQLiteDatabase db = cache.getWritableDatabase();

// Write to DB
ContentValues values = new ContentValues();
values.put(REQUEST_TIMESTAMP, TEST_TIME); 
values.put(REQUEST_URL, TEST_URL);
db.insertOrThrow(TABLE_NAME, null, values);

// Read from DB and compare values      
Vector<Request> matchingRequests = new Vector<Request>();
db = cache.getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME, SEARCH_URL_RETURN_COLUMNS, SEARCH_URL_WHERE, new String[] {url}, null, null, ORDER_BY, null);
int id = 0;

while(cursor.moveToNext()) {
    long timestamp = cursor.getLong(0);
    Request request = new Request(id++);
    request.setUrl(url);
    request.setCreationTimestamp(new Date(timestamp));
    matchingRequests.add(request);
}


// Assert that one row is returned
assertThat(matchingRequests.size(), equalTo(1));  // fails, size() returns 0

当在robolectric之外调试代码时,这是预期的。我做错了什么吗?还是不能使用Robolectric测试SQlite数据库?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-02-05 00:04:02

注意:此答案已过时。如果您使用的是Roboletal2.x,请参阅https://stackoverflow.com/a/24578332/850787

问题是,Robolectric的SQLiteDatabase只存储在内存中,所以当您调用getReadableDatabase或getWritableDatabase时,现有的数据库将被新的空数据库覆盖。

我遇到了同样的问题,我找到的唯一解决方案是,如果给出两次相同的上下文,我需要派生Robolectric项目,并添加ShadowSQLiteOpenHelper来保存数据库。然而,我的fork的问题是,当给定contex时,我必须“禁用”close()-function,因为否则Connection.close()将破坏内存中的数据库。我已经为它做了拉取请求,但它还没有合并到项目中。

但是请随意克隆我的版本,它应该可以解决您的问题(如果我理解正确:P )。它可以在GitHub上找到:https://github.com/waltsu/robolectric

以下是如何使用修改的示例:

代码语言:javascript
复制
Context c = new Activity(); 
SQLiteOpenHelper helper = new SQLiteOpenHelper(c, "path", null, 1); 
SQLiteDatabase db = helper.getWritableDatabase(); 
// With the db write something to the database 
db.query(...); 
SQLiteOpenHelper helper2 = new SQLiteOpenHelper(c, "path", null, 1); 
SQLitedatabase db2 = helper2.getWritableDatabase(); 
// Now db and db2 is actually the same instance 
Cursor c = db2.query(...) ; // Fetch the data which was saved before 

当然,您不需要创建新的SQLiteOpenHelper,但这只是一个例子,将相同的上下文传递给两个不同的SQLiteOpenHelper将得到相同的数据库。

票数 10
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7320820

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档