Skip to content

Instantly share code, notes, and snippets.

@JLWalsh
Last active August 20, 2020 17:46
Show Gist options
  • Save JLWalsh/a31702c91451f8704106a0ac4eb3e39c to your computer and use it in GitHub Desktop.
Save JLWalsh/a31702c91451f8704106a0ac4eb3e39c to your computer and use it in GitHub Desktop.
Mockk equality matcher that uses reflection to verify equality of two objects. Useful when testing objects that don't offer an equals() method. Requires org.apache.commons
import io.mockk.Matcher
import io.mockk.MockKMatcherScope
import org.apache.commons.lang3.builder.EqualsBuilder
class ReflectedEqualityMatcher<T>(
private val expected: T
) : Matcher<T> {
override fun match(arg: T?): Boolean {
if (arg == null) {
return false
}
return EqualsBuilder()
.setTestRecursive(true)
.setTestTransients(true)
.reflectionAppend(expected, arg)
.isEquals
}
}
inline fun <reified T : Any> MockKMatcherScope.reflectedEq(expected: T): T = match(ReflectedEqualityMatcher(expected))
// Example usage
val expected = XYZ()
verify { someService.doSomething(reflectedEq(expected)) }
// Unit tests
class ReflectedEqualityMatcherTest {
@Test
fun `given two objects with differing values, when matching, should not match objects`() {
val expected = ComparisonStub(field = "123", anotherField = "456")
val actual = ComparisonStub(field = "123", anotherField = "912")
val matcher = ReflectedEqualityMatcher(expected)
assert(matcher.match(actual)).isFalse()
}
@Test
fun `given two objects with same values, when matching, should match objects`() {
val expected = ComparisonStub(field = "123", anotherField = "456")
val actual = ComparisonStub(field = "123", anotherField = "456")
val matcher = ReflectedEqualityMatcher(expected)
assert(matcher.match(actual)).isTrue()
}
@Test
fun `given two objects with differing values in nested field, when matching, should not match objects`() {
val expected = NestedComparisonStub(ComparisonStub(field = "123", anotherField = "456"))
val actual = NestedComparisonStub(ComparisonStub(field = "abc", anotherField = "456"))
val matcher = ReflectedEqualityMatcher(expected)
assert(matcher.match(actual)).isFalse()
}
@Test
fun `given two objects with same values in nested field, when matching, should match objects`() {
val expected = NestedComparisonStub(ComparisonStub(field = "123", anotherField = "456"))
val actual = NestedComparisonStub(ComparisonStub(field = "123", anotherField = "456"))
val matcher = ReflectedEqualityMatcher(expected)
assert(matcher.match(actual)).isTrue()
}
private class ComparisonStub(
private val field: String,
val anotherField: String
)
private class NestedComparisonStub(
private val nestedClass: ComparisonStub
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment