Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin unit testing high order function in data class fails when passing lambda argument

data class DataSample(val name: String, val exec: () -> Unit = {})

I am trying to understand why the following test would fail:

@Test
fun `testing data fails`() {
    val dataOne = DataSample("the_same") {
    }
    val dataTwo = DataSample("the_same") {
    }
    assertEquals(dataOne, dataTwo)
}

and the following would pass:

@Test
fun `testing data pass`() {
    val dataOne = DataSample("the_same")
    val dataTwo = DataSample("the_same")
    assertEquals(dataOne, dataTwo)
}

The test will pass when the lambda is omitted and it fails when one is provided.

like image 206
Rodrigo Queiroz Avatar asked Sep 14 '25 11:09

Rodrigo Queiroz


1 Answers

Since instances of data classes are compared member by member the first test succeeds because “the same“ is equal to “the same“ and the default value for exec is {} which is equal to itself. In the second test you give each instance its own lambda which are not equal to each other even though they behave equally. Thus, comparing dataOne and dataTwo fails.

like image 151
johanneslink Avatar answered Sep 17 '25 18:09

johanneslink