Search code examples
kotlinjunitmockito

How to ignore a lambda when comparing for equality?


Given this class:

data class MyClass(
    val foo: String,
    val bar: () -> Unit
)

I want to assert that two instances of MyClass are equal, ignoring the lambda field bar. How do I make this work with Mockito?

Here's the code that doesn't work:

        val actual = MyClass("foo", bar = {})
        val expected = MyClass("foo", bar = Mockito.any())

        assertEquals(expected, actual)

Solution

  • Without changing the Class:

    1. You could create the expected by copying the actual field. For example:

      val expected = actual.copy(foo = "foo")
      
    2. If the object is instantiated elsewhere, then you could create a copy of the actual field. For example:

      assertEquals(expected, actual.copy(bar = expected.bar)
      

    Changing the Class:

    1. Only fields inside the primary constructor are taken into account when building the equals method. You could remove the bar field from the primary constructor. For example:

      data class MyClass(
          val foo: String
      ) {
          val bar: () -> Unit = {}
      }
      
    2. You could override the equals method in the class. For example:

      data class MyClass(
          val foo: String,
          val bar: () -> Unit
      ) {
          override fun equals(other: Any?): Boolean {
              return (other as? MyClass)?.foo == foo
          }
      
          override fun hashCode(): Int {
              return foo.hashCode()
          }
      }