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!
}
I'm using JUnit 4.8.1.
assertSame
takes twoObject
arguments, and so the compiler has to autobox yourint
literals intoInteger
.This is equivalent to
Now for values between -128 and 127, the JVM will cache the results of
Integer.valueOf
, so you get the sameInteger
object back each time. For values outside of that range, you get new objects back.So for
assertSame(127, 127)
, JUnit is comparing the same objects, hence it works. ForassertSame(128, 128)
, you get different objects, so it fails.Just another reason to be careful with autoboxing.
The reason is the autoboxing of Java. You use the method:
It only works with Objects. When you pass
int
s to this method, Java automatically callswith these values. So the cast to
int
has no effect.For values less than 128 Java has a cache, so
assertSame()
compares theInteger
object with itself. For values greater than 127 Java creates new instances, soassertSame()
compares anInteger
object with another. Because they are not the same instance, theassertSame()
method returns false.You should use the method:
instead. This method uses the
equals()
method fromObject
.