Reputation: 12524
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?
Upvotes: 12
Views: 35413
Reputation: 237
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.
Upvotes: 1
Reputation: 726987
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());
Upvotes: 22