如何使用数据库编写Robolectric(2.3)测试

时间:2014-05-22 13:46:03

标签: android sqlite unit-testing robolectric

由于Robolectic最后一次发布到版本2.3,它写了(https://github.com/robolectric/robolectric/releases):

  

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

我还没找到任何"如何"文档。 我想知道如何实施测试,例如使用SQLiteDatabase查询的活动。我应该把.db文件放在哪里,以便测试使用它。

2 个答案:

答案 0 :(得分:15)

您需要将.db文件放在src/test/resources/文件夹下。

例如,sample.db

然后在你的单元测试setUp()中调用:

@Before
public void setUp() throws Exception {
    String filePath = getClass().getResource("/sample.db").toURI().getPath();

    SQLiteDatabase db = SQLiteDatabase.openDatabase(
        (new File(filePath)).getAbsolutePath(), 
        null, 
        SQLiteDatabase.OPEN_READWRITE);

   // perform any db operations you want here
}

答案 1 :(得分:-1)

以下是如何测试数据库,操作的示例。

    // just a wrapper for the content values map
    Agenda agenda = new Agenda();
    agenda.setName("MyAgenda");
    agenda.setDate("current date");

    long rowId = agendaManager.insert(agenda); // the guy who makes database operations

    Cursor query = context.getContentResolver().query(AgendaProvider.AGENDA_CONTENT_URI, null, null, null, null);
    assertThat(query.getCount()).isEqualTo(1);
    query.moveToNext();
    Agenda dbAgenda = new Agenda(query);
    assertThat(dbAgenda.getRowId()).isPositive();
    assertThat(dbAgenda.getRowId()).isEqualTo(rowId);
    assertThat(dbAgenda.getName()).isEqualTo(agenda.getName());
    assertThat(dbAgenda.getDate()).isEqualTo(agenda.getDate());

可在此处找到更详细的示例https://github.com/nenick/android-gradle-template/blob/master/UnitTestsRobolectric/src/test/java/com/example/managers/AgendaManagerTest.java