JUnit - assertSame [英] JUnit - assertSame
问题描述
当我使用值> 127时,有人能告诉我为什么assertSame()失败了吗?
Can someone tell me why assertSame() do fail when I use values > 127?
import static org.junit.Assert.*;
...
@Test
public void StationTest1() {
..
assertSame(4, 4); // OK
assertSame(10, 10); // OK
assertSame(100, 100); // OK
assertSame(127, 127); // OK
assertSame(128, 128); // raises an junit.framework.AssertionFailedError!
assertSame(((int) 128),((int) 128)); // also junit.framework.AssertionFailedError!
}
我正在使用JUnit 4.8.1。
I'm using JUnit 4.8.1.
推荐答案
原因是Java的自动装箱。
您使用以下方法:
The reason is the autoboxing of Java. You use the method:
public static void assertSame(Object expected, Object actual)
它仅适用于Objects。当您将 int
传递给此方法时,Java会自动调用
It only works with Objects. When you pass int
s to this method, Java automatically calls
Integer.valueOf( int i )
这些值。因此转换为 int
无效。
with these values. So the cast to int
has no effect.
对于小于128的值,Java有一个缓存,所以 assertSame()
将 Integer
对象与自身进行比较。对于大于127的值,Java会创建新实例,因此 assertSame()
将 Integer
对象与另一个对象进行比较。因为它们不是同一个实例,所以 assertSame()
方法返回false。
For values less than 128 Java has a cache, so assertSame()
compares the Integer
object with itself. For values greater than 127 Java creates new instances, so assertSame()
compares an Integer
object with another. Because they are not the same instance, the assertSame()
method returns false.
您应该使用以下方法:
You should use the method:
public static void assertEquals(Object expected, Object actual)
。此方法使用 Object
中的 equals()
方法。
instead. This method uses the equals()
method from Object
.
这篇关于JUnit - assertSame的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!