JUnit - assertSame

Michael W. picture Michael W. · May 21, 2010 · Viewed 20.8k times · Source

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.

Answer

Daniel Engmann picture Daniel Engmann · May 21, 2010

The reason is the autoboxing of Java. You use the method:

public static void assertSame(Object expected, Object actual)

It only works with Objects. When you pass ints to this method, Java automatically calls

Integer.valueOf( int i )

with these values. So the cast to int has no effect.

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)

instead. This method uses the equals() method from Object.