Java JUnit - assertSame
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2882337/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JUnit - assertSame
提问by Michael W.
Can someone tell me why assertSame() do fail when I use values > 127?
有人能告诉我为什么当我使用值 > 127 时 assertSame() 会失败吗?
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!
}
I'm using JUnit 4.8.1.
我正在使用 JUnit 4.8.1。
采纳答案by Daniel Engmann
The reason is the autoboxing of Java. You use the method:
原因是Java的自动装箱。您使用以下方法:
public static void assertSame(Object expected, Object actual)
It only works with Objects. When you pass int
s to this method, Java automatically calls
它只适用于对象。当您将int
s传递给此方法时,Java 会自动调用
Integer.valueOf( int i )
with these values. So the cast to int
has no effect.
有了这些价值观。所以演员表int
没有效果。
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.
对于小于 128 的值,Java 具有缓存,因此assertSame()
将Integer
对象与其自身进行比较。对于大于 127 的值,Java 创建新实例,因此assertSame()
将一个Integer
对象与另一个对象进行比较。因为它们不是同一个实例,所以该assertSame()
方法返回 false。
You should use the method:
您应该使用以下方法:
public static void assertEquals(Object expected, Object actual)
instead. This method uses the equals()
method from Object
.
反而。此方法使用equals()
来自的方法Object
。
回答by skaffman
assertSame
takes two Object
arguments, and so the compiler has to autobox your int
literals into Integer
.
assertSame
需要两个Object
参数,因此编译器必须将您的int
文字自动装箱到Integer
.
This is equivalent to
这相当于
assertSame(Integer.valueOf(128), Integer.valueOf(128));
Now for values between -128 and 127, the JVM will cache the results of Integer.valueOf
, so you get the same Integer
object back each time. For values outside of that range, you get new objects back.
现在,对于 -128 到 127 之间的值,JVM 将缓存 的结果Integer.valueOf
,因此您Integer
每次都返回相同的对象。对于超出该范围的值,您将获得新对象。
So for assertSame(127, 127)
, JUnit is comparing the same objects, hence it works. For assertSame(128, 128)
, you get different objects, so it fails.
因此,对于assertSame(127, 127)
,JUnit 正在比较相同的对象,因此它可以工作。对于assertSame(128, 128)
,你得到不同的对象,所以它失败了。
Just another reason to be careful with autoboxing.
这是小心自动装箱的另一个原因。