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?
Overview. Asserting that an int equals an Integer is not possible with assertEquals() due to the compiler not knowing if it should use assertEquals(int, int) or assertEquals(Object, Object) .
Procedure assertEquals has two parameters, the expected-value and the computed-value, so a call looks like this: assertEquals(expected-value, computed-value);
IIRC assertEquals() succeeds if both strings are null. If this is not what you want then call assertNotNull() as well.
assertEquals() Asserts that two objects are equal. assertSame() Asserts that two objects refer to the same object. the assertEquals should pass and assertSame should fail, as the value of both classes are equal but they have different reference location.
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());
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With