How do I compare Integer and Long types with Junit ?
The result of assertThat(poiList.get(0).get("id_pk")).isEqualTo(member.getId_pk());
is:
org.opentest4j.AssertionFailedError:
expected: 1L
but was : 1
Expected :1L
Actual :1
The two types are:
log.info("getClass1: {}", poiList.get(0).get("id_pk").getClass());
log.info("getClass2: {}", member.getId_pk().getClass());
2021-09-30 15:29:08.904 INFO 19504 --- [ main] c.p.i.domain.item.ItemServiceTest : getClass1: class java.lang.Integer
2021-09-30 15:29:08.904 INFO 19504 --- [ main] c.p.i.domain.item.ItemServiceTest : getClass2: class java.lang.Long
How can I compare 1 and 1L to be equal?
best regards
CodePudding user response:
You can convert Integer to Long via java.lang.Integer#longValue
:
assertThat(poiList.get(0).get("id_pk").longValue()).isEqualTo(member.getId_pk());
BUT beware of Null pointers, if poiList.get(0).get("id_pk")
is null then a Null Pointer Exception will be thrown!
CodePudding user response:
Looks like it should be corrected at entity level because if we say poiList.get(0).get("id_pk")
is equal to member.getId_pk()
then logically datatype for them should also be same.
As the preferred solution you should correct it entity level.
But if you still want to assert it then convert int
to long
first and then assert on that.
poiList.get(0).get("id_pk").longValue()
CodePudding user response:
Two ways:
Java's Long class has an .intValue() method returning an int.
Java's Integer class has a .longvalue() method.
I would recommend the second, as long can take a larger range of values than int.
CodePudding user response:
How about this:
assertThat(new BigDecimal(1)).isEqualTo(new BigDecimal(1L));
CodePudding user response:
As all answers show, you need to change one param's type. Maybe both change them to String is also a good idea.
assertThat(String.valueOf(1L)).isEqualTo(String.valueOf(1))