Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can assertEquals(Long,Integer) succeed?

Tags:

java

junit

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?

like image 298
s_bei Avatar asked Jul 04 '13 10:07

s_bei


People also ask

Does assertEquals work for integers?

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) .

How many arguments can a assertEquals method have?

Procedure assertEquals has two parameters, the expected-value and the computed-value, so a call looks like this: assertEquals(expected-value, computed-value);

Can you use assertEquals for strings?

IIRC assertEquals() succeeds if both strings are null. If this is not what you want then call assertNotNull() as well.

What is the difference between assertSame and assertEquals?

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.


2 Answers

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());
like image 156
Sergey Kalinichenko Avatar answered Nov 05 '22 15:11

Sergey Kalinichenko


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.

like image 30
Akunosh Avatar answered Nov 05 '22 16:11

Akunosh