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)
Without changing the Class:
You could create the expected
by copying the actual
field. For example:
val expected = actual.copy(foo = "foo")
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:
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 = {}
}
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()
}
}