user3826764
user3826764

Reputation: 336

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. After adding a row, the count always remains 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)
}

Upvotes: 0

Views: 127

Answers (1)

MikeT
MikeT

Reputation: 57073

If you omit the assertEquals and the @Test then there is no issue.

i.e. 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)

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

Upvotes: 0

Related Questions