简体   繁体   中英

Can assertEquals(Long,Integer) succeed?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM