11

Currently I am doing some code review and I found this line of code which interrupts the testcase:

assertEquals(Long.valueOf(4321), lMessage.getNumber());

getNumber returns an Integer which is also 4321. I changed it to this:

assertTrue(4321 == lSavedStoerung.getMessage());

because in my understanding of the equals method the assertEquals can never return true in the first example. With my assertTrue all test cases running fine.

Or did I understand something wrong?

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
nano_nano
  • 12,351
  • 8
  • 55
  • 83
  • 1
    Are you sure that having method return an `Integer` instead of a `Long` is not a mistake? – svz Jul 04 '13 at 10:53
  • getNumber returns Integer. I am absolutly sure about that. – nano_nano Jul 04 '13 at 10:56
  • assertEquals() is generally better than assertTrue() because when your test fails, the output will contain both the expected and actual value. – Tore Olsen Jul 04 '13 at 11:11

2 Answers2

22

The reason why assertEquals test has failed is that equality considers not only the value of the number, but also its type. java.lang.Long object does not compare as equal to a java.lang.Integer.

Since lMessage.getNumber() returns an int, Java wraps it into Integer before passing to assertEquals. That's why you could fix the test case by using Integer.valueOf instead:

assertEquals(Integer.valueOf(4321), lMessage.getNumber());
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

What is the reason behind 4321 being a long? If it's not necessary use the integer solution dasblinkenlight sugested.

assertEquals(Integer.valueOf(4321), lMessage.getNumber());

or

assertEquals(4321, lMessage.getNumber());

On the other hand, if your code allows lMessage.getNumber() return a long depending on the circumstances then you could box it into a long for your test.

assertEquals(Long.valueOf(4321), (long) lMessage.getNumber());

PS: Getting too compfortable using assertTrue & == will cause you trouble if you ever compare something that does not come in a primitive data type, but it will not in this specific example.

Akunosh
  • 237
  • 1
  • 2
  • 10