使用Mockito比较Kotlin Data Class时如何忽略Lambda字段?
解决方法
你的代码无法工作的原因是:Mockito.any() 是用于Mock方法调用时的参数匹配器,它返回的是一个占位符对象,并非真正的Lambda实例。而Kotlin data class的equals方法会比较所有字段,所以用Mockito.any()创建的expected实例,其bar字段和actual的空Lambda完全不是一回事,断言自然失败。
要实现忽略bar字段的相等断言,用Mockito可以这样做:
方法1:自定义ArgumentMatcher匹配器
创建一个自定义的匹配器,只校验foo字段是否相等:
import org.mockito.ArgumentMatcher class MyClassIgnoringBarMatcher(private val expected: MyClass) : ArgumentMatcher<MyClass> { override fun matches(actual: MyClass?): Boolean { return actual != null && actual.foo == expected.foo // 完全忽略bar字段的比较 } }
然后在测试中使用这个匹配器:
val actual = MyClass("foo", bar = {}) val expected = MyClass("foo", bar = {}) // bar字段随便填,匹配器会忽略 Mockito.assertThat(actual, argThat(MyClassIgnoringBarMatcher(expected)))
方法2:简化的Lambda式匹配器
如果不想单独写匹配器类,可以直接用Lambda简化:
val actual = MyClass("foo", bar = {}) val expectedFoo = "foo" Mockito.assertThat(actual, argThat { it.foo == expectedFoo })
方法3:直接断言目标字段
其实如果只是要校验foo相等,完全可以不用复杂的匹配器,直接断言字段值:
val actual = MyClass("foo", bar = {}) assertEquals("foo", actual.foo)
这种方式更直接,也不需要依赖Mockito的匹配器功能。
内容的提问来源于stack exchange,提问作者user2892437
相关产品推荐
相关产品推荐

