4

I have the following code in a junit test case. The first Assert passes and the second one fails.

final int code = webResponse.getResponseCode();
Assert.assertTrue(200 == code);  //passes
Assert.assertSame(200, code);    //fails

Why does the second one fail? webResponse is type WebResponse and all implementations of getResponseCode return an int.

I am running the code within a junit test and the second assert fails in both Intellij and Eclipse IDE. Also, in Intellij, it provides a link to "Click to see difference" but when I click that, it says "Contents are identical".

Eric Leschinski
  • 135,913
  • 89
  • 401
  • 325
jlars62
  • 6,816
  • 7
  • 37
  • 57

1 Answers1

9

assertSame(Object, Object) checks if both arguments refer to the same object.

It performs boxing conversion to convert 200 to a valid reference type object. To do this, it does

Integer.valueOf(200);

and

Integer.valueOf(code);

which return new object references which do not reference the same object.

Sotirios Delimanolis
  • 263,859
  • 56
  • 671
  • 702
  • More about it is here http://stackoverflow.com/questions/2882337/junit-assertsame – T.G Jun 12 '14 at 15:53
  • Oh ok good to know, I had thought to use assertSame when I wanted to use `==` and assertEquals when I wanted to use `.equals`. But I see now that I should use assertSame only when comparing two references. – jlars62 Jun 12 '14 at 15:55
  • @jlars62 `assertSame()` here would actually worked if code had been between -128 and 127 due to `Integer` caching. – awksp Jun 12 '14 at 15:58
  • @user3580294 Oh ok. That makes sense. Thank you that's a great tip! – jlars62 Jun 12 '14 at 16:00