【发布时间】:2019-02-05 20:02:55
【问题描述】:
假设我有一个界面
interface IFoo{
val foo:String
}
并且我想创建与它们的foo 字符串匹配的IFF 相等的类。
简单示例:
class A(override val foo:String):IFoo{
val somethingIrrelevant = "bar"
override fun equals(other: Any?): Boolean {
return if(other is IFoo) foo == other.foo else false
}
override fun hashCode(): Int {
return Objects.hash(foo)
}
}
看起来比较简单,但是这个测试用例:
@Test
fun mockingEquality(){
//given
val a = A("alpha")
val b = A("alpha")
assertThat(a,`is`(b)) //succeeds
//when
val c = mock(A::class.java)
whenever(c.foo).thenReturn("alpha")
//then
assertThat(c, `is`(a)) //fails
}
失败
Expected: is <A@589b17d>
but: was <Mock for A, hashCode: 263885523>
这是为什么呢?
以及我如何正确模拟 A 类以使该测试成功?
【问题讨论】:
标签: unit-testing junit kotlin mockito hamcrest