android - 在 Robolectric 中测试 SQLite 数据库

标签 android sqlite robolectric

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

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

// 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 数据库?

最佳答案

Robolectric 2.3 使用 SQLite 的真实实现,而不是阴影和伪造品的集合。现在可以编写测试来验证真实的数据库行为。

关于android - 在 Robolectric 中测试 SQLite 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7320820/

相关文章:

iphone - 是否可以将800x1067像素的图像(约270 kb)存储到sqlite/Core Data中?

android - 如何在android中使用Service更新sqlite数据库

android - ContentProvider - 返回多个游标或自定义对象

android - 如何通过 Robolectric 以编程方式获取自定义主题值

android - 有人在 IntelliJ 上使用没有 Maven 的 Robolectric 吗?

android - 如何在锁屏上显示您的应用程序?

java - Android 认为我没有关闭我的数据库!为什么?

java - Box2D 和引擎 : app hangs out when creating Joints during ContactListener?

android - 为什么Android会在Orientation Change上重新创建 Activity

android - 从 IDEA 运行 Robolectric 测试