Robolectric:使用ormlite进行测试

jel*_*ies 3 testing android dao ormlite robolectric

我正在尝试使用robolectric测试ORMLite DAO,但数据库行为与从我的Android应用程序中使用它时的行为不同.我的DAO在Android应用程序上运行得非常好.

阅读robolectric阴影和调试代码,我遇到了ShadowSQLiteOpenHelper(这里的代码).

有谁知道这个暗影是否足以测试ormlite daos?或者我必须创建自己的影子才能实现这一目标?这里有任何线索/提示/建议/示例吗?

提前致谢.


额外信息:

测试方法:

@Test
public void basicTest() throws SQLException {
    assertNotNull(randomStringResource); // Injection of an android resource: OK
    assertThat(randomStringResource, equalTo("Event")); // With correct value: OK
    assertNotNull(eventDao); // Dao injection: OK
    assertThat(eventDao.countOf(), equalTo(0L)); // Table empty: OK

    Event e1 = new Event("e1", new Date());
    eventDao.create(e1);

    assertNotNull(e1.getId()); // ID generated by OrmLite: OK
    assertThat(eventDao.countOf(), equalTo(1L)); // Table not empty: OK
    assertThat("e1", equalTo(eventDao.queryForId(e1.getId()).getName())); // Query for inserted event: Throws exception
}
Run Code Online (Sandbox Code Playgroud)

运行此测试时遇到的一些问题:

  • 查询具有"camelCased"属性名称的实体的错误:在最后一行测试时抛出错误(相关问题).从来没有像运行Android应用程序这样的问题.
  • 当我更改其中一个属性名称(例如,isEnabledto enabled)以避免camelCase问题时,之前的错误仍然存​​在...似乎内存数据库没有应用我在实体上所做的更改.

使用的版本:

  • Robolectric 1.1
  • OrmLite 4.41

小智 6

很抱歉复活你的主题,但我遇到了同样的问题.

我正在使用OrmLite 4.45和Robolectric 2.1.

ShadowSQLiteCursor.java中,cacheColumnNames方法调用toLowerCase每个列名.所以我决定ShadowSQLiteCursor用自己的(不调用toLowerCase)扩展:

/**
* Simulates an Android Cursor object, by wrapping a JDBC ResultSet.
*/
@Implements(value = SQLiteCursor.class, inheritImplementationMethods = true)
public class ShadowCaseSensitiveSQLiteCursor extends ShadowSQLiteCursor {

private ResultSet resultSet;

public void __constructor__(SQLiteCursorDriver driver, String editTable, SQLiteQuery query) {}

/**
 * Stores the column names so they are retrievable after the resultSet has closed
 */
private void cacheColumnNames(ResultSet rs) {
    try {
        ResultSetMetaData metaData = rs.getMetaData();
        int columnCount = metaData.getColumnCount();
        columnNameArray = new String[columnCount];
        for(int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
            String cName = metaData.getColumnName(columnIndex);
            this.columnNames.put(cName, columnIndex - 1);
            this.columnNameArray[columnIndex - 1] = cName;
        }
    } catch(SQLException e) {
        throw new RuntimeException("SQL exception in cacheColumnNames", e);
    }
}
}
Run Code Online (Sandbox Code Playgroud)

我的答案显然来得太晚,但可能会帮助别人!