简体   繁体   English

assertEquals(Long,Integer)是否可以成功?

[英]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 . getNumber返回一个也是4321Integer 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. 因为根据我对equals方法的理解, assertEquals在第一个示例中永远不会返回true。 With my assertTrue all test cases running fine. 使用我的assertTrue所有测试用例都运行良好。

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. assertEquals测试失败的原因是,相等性不仅考虑数字的值,还考虑其类型。 java.lang.Long object does not compare as equal to a java.lang.Integer . java.lang.Long对象不equal java.lang.Integer

Since lMessage.getNumber() returns an int , Java wraps it into Integer before passing to assertEquals . 由于lMessage.getNumber()返回一个int ,因此Java在传递给assertEquals之前将其包装为Integer That's why you could fix the test case by using Integer.valueOf instead: 这就是为什么您可以使用Integer.valueOf来修复测试用例的原因:

assertEquals(Integer.valueOf(4321), lMessage.getNumber());

What is the reason behind 4321 being a long? 4321过长的原因是什么? If it's not necessary use the integer solution dasblinkenlight sugested. 如果没有必要,请使用整数解决方案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. 另一方面,如果您的代码允许lMessage.getNumber()根据情况返回长lMessage.getNumber() ,则可以将其lMessage.getNumber()以进行测试。

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. PS:使用assertTrue&==过于自在时,如果您比较原始数据类型中未包含的内容,则会给您带来麻烦,但在此特定示例中不会。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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