【发布时间】:2015-11-26 15:06:06
【问题描述】:
考虑以下使用标准 JUnit 断言和 hamcrest 的 assertThat 的测试用例:
byte b = 0;
int i = 0;
assertEquals(b, i); // success
assertThat(b, equalTo(i)); // java.lang.AssertionError: Expected: <0> but: was <0>
if (b == i) {
fail(); // test fails, so b == i is true for the JVM
}
为什么会这样?对于 JVM,这些值显然是相等的,因为 b == i 是 true,那么为什么 hamcrest 会失败?
【问题讨论】:
-
因为
Byte.valueOf((byte) 0).equals(Integer.valueOf(0))是假的。 -
如在上面的 assylias 示例中所见,字节被自动装箱成一个字节对象。如Hamcrest's equalTo docs 中所见,它使用 Object1.equals(Object2)。由于 byte 和 int 都是原语,因此它将它们自动装箱为 Byte 和 Integer 对象。 Byte1.equals(Integer1) 将返回 false,即使这些装箱对象的值相同。