Robolectric + SQLiteStatement.executeUpdateDelete()不执行任何操作

时间:2013-04-01 22:51:00

标签: android sqlite robolectric

我需要在表中增加一些整数。 而不是进行选择和连续更新,我想通过单个查询来做到这一点。 但是运气不好。

以下代码返回0:

final SQLiteStatement stmt = helper.getWritableDatabase().
    compileStatement("update my_table set my_count = my_count + 1 where _id = ?");
try
{
    stmt.bindLong(1, id);
    return stmt.executeUpdateDelete();
}
finally
{
    stmt.close();
}

当然,没有记录更新。

但这会返回1:

final ContentValues v = new ContentValues();
v.put("my_count", 1);
return helper.getWritableDatabase().
    update("my_table", v, "_id=?", new String[]{String.valueOf(id)});

指定ID的记录存在100%。 尝试在交易内或交易中进行此操作 - 结果相同。 没有测试真正的SQLiteStatement,可能是Robolectric bug。

有人对此影响有任何假设吗? 或者有关如何解决此问题的建议(可能没有使用SQLiteStatement)?

感谢。

更新1。

我还要做一些简单的测试:

@RunWith(RobolectricTestRunner.class)
public class SQLiteStatementTest
{

    private static class TestOpenHelper extends SQLiteOpenHelper
    {
        public TestOpenHelper(Context context)
        {
            super(context, "test", null, 1);
        }

        @Override
        public void onCreate(SQLiteDatabase db)
        {
            db.execSQL("CREATE TABLE test(_id INTEGER PRIMARY KEY AUTOINCREMENT, count INTEGER)");
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
        {
        }
    }

    @Test
    public void testExecuteUpdateDeleteModifiesRow() throws Exception
    {
        final int initialCount = 6;
        final TestOpenHelper helper = new TestOpenHelper(Robolectric.application);

        final ContentValues v = new ContentValues();
        v.put("count", initialCount);
        final long id = helper.getWritableDatabase().insert("test", null, v);

        final SQLiteStatement stmt = helper.getWritableDatabase().
            compileStatement("update test set count = count + 1 where _id=?");

        stmt.bindLong(1, id);
        assertThat(stmt.executeUpdateDelete(), is(1));

    }
}

1 个答案:

答案 0 :(得分:0)

根据以下消息来源:

https://github.com/pivotal/robolectric/blob/master/src/main/java/org/robolectric/shadows/ShadowSQLiteStatement.java

executeUpdateDelete()未实施。

由于callThroughByDefault = false此方法被默认空实现所遮蔽。这就是为什么我没有得到RuntimeException("Stub!")

隐藏此方法应该很容易,但我在robolectric Uri.parse

中找到了more general problem(带2.0-alpha-2方法)

更新1。

将请求提取到影子executeUpdateDelete()
https://github.com/pivotal/robolectric/pull/450
https://github.com/pivotal/robolectric/pull/451