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

lig*_*ght 5 sqlite android unit-testing robolectric

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

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

我还没有找到任何"如何"文档.我想知道如何使用SQLiteDatabase查询在Activity上实现测试.我应该把.db文件放在哪里,以便测试使用它.

lor*_*ong 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
}
Run Code Online (Sandbox Code Playgroud)