【问题标题】:How to write Robolectric (2.3) test using database如何使用数据库编写 Robolectric (2.3) 测试
【发布时间】:2014-05-22 13:46:03
【问题描述】:

由于 Robolectic 的最新版本是 2.3 版,因此写成 (https://github.com/robolectric/robolectric/releases):

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

我没有找到任何“操作方法”文档。 我想知道我应该如何实施测试,例如活动使用 SQLiteDatabase 查询。我应该把 .db 文件放在哪里,以便测试使用它。

【问题讨论】:

    标签: android sqlite unit-testing robolectric


    【解决方案1】:

    您需要将 .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
    }
    

    【讨论】:

      【解决方案2】:

      这是一个如何测试数据库、操作的示例。

          // 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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-08-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-12-04
        • 1970-01-01
        相关资源
        最近更新 更多