简体   繁体   English

Android MatrixCursor 不添加新行

[英]Android MatrixCursor not adding new row

I need to mock a Cursor for some content provider unit tests, but the addRow method is not working for some strange reason.我需要模拟 Cursor 以进行某些内容提供程序单元测试,但addRow方法由于某些奇怪的原因无法正常工作。 After adding a row, the count always remains 0.添加一行后,计数始终保持为 0。

What am I missing?我错过了什么?

@Test
fun addCursorTest() {
    val columns: Array<String> = arrayOf(
        "name",
        "age"
    )
    val matrixCursor : Cursor = MatrixCursor(columns).apply {
        addRow(arrayOf("name1", 18))
        addRow(arrayOf("name2", 26))
    }
    println("cursor count = ${matrixCursor.count}") //prints "cursor count = 0"
    assertEquals(2, matrixCursor.count)
}

If you omit the assertEquals and the @Test then there is no issue.如果省略assertEquals和 @Test 则没有问题。

ie using:-即使用:-

@SuppressLint("Range")
fun addCursorTest() {
    val columns: Array<String> = arrayOf(
        "name",
        "age"
    )
    val matrixCursor : Cursor = MatrixCursor(columns).apply {
        addRow(arrayOf("name1", 18))
        addRow(arrayOf("name2", 26))
    }
    Log.d("CURSORINFO","Cursor Count is ${matrixCursor.count}")
    while (matrixCursor.moveToNext()) {
        val sb = StringBuilder()
        for (s in matrixCursor.columnNames) {
            sb.append("\n\tColumn is ${s} Value is ")
            sb.append(matrixCursor.getString(matrixCursor.getColumnIndex(s))).append(" ")
        }
        Log.d("CURSORINFO",sb.toString())
    }
    println("cursor count = ${matrixCursor.count}") //prints "cursor count = 0"
    //assertEquals(2, matrixCursor.count)
}
  • @SuppressLint("Range") added as for whatever reason the potential for a -1 (column not found result from getColumnIndex(the_column) results in a range error, of course just will not happen when traversing the columns in the actual Cursor unless the Cursor has been corrupted) @SuppressLint("Range")添加了无论出于何种原因 -1 的可能性( getColumnIndex(the_column)导致范围错误的结果未找到列,当然在遍历实际 Cursor 中的列时不会发生,除非Cursor 已损坏)

results in the log including:-日志中的结果包括:-

2023-06-09 10:17:29.550 D/CURSORINFO: Cursor Count is 2
2023-06-09 10:17:29.551 D/CURSORINFO:   Column is name Value is name1 
        Column is age Value is 18 
2023-06-09 10:17:29.551 D/CURSORINFO:   Column is name Value is name2 
        Column is age Value is 26 
2023-06-09 10:17:29.551 I/System.out: cursor count = 2

You may wish to refer to assertEquals not working as expected with Set in Kotlin您可能希望参考Kotlin 中的 assertEquals not working as expected with Set

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM