JUnit - assertSame

后端 未结 2 875
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-30 23:29

Can someone tell me why assertSame() do fail when I use values > 127?

        import static org.junit.Assert.*;

        ...

        @Test
        public vo         


        
相关标签:
2条回答
  • 2020-12-30 23:43

    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.

    0 讨论(0)
  • 2020-12-30 23:51

    assertSame takes two Object arguments, and so the compiler has to autobox your int literals into 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.

    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.

    Just another reason to be careful with autoboxing.

    0 讨论(0)
提交回复
热议问题