Java assertTrue 与“instanceof” vs assertEquals
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23287702/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
assertTrue with "instanceof" vs assertEquals
提问by quarks
I wonder why this fails:
我想知道为什么这会失败:
assertEquals(Key.class, expectedKey.getClass());
and this does not:
这不会:
assertTrue(expectedKey instanceof Key);
Is there a real difference between the two?
两者之间有真正的区别吗?
采纳答案by JB Nizet
Because expectedKeyis an instance of a subclassof Key, most probably. The error message you get from the failed assertion should tell you. Read it.
因为expectedKey是Key子类的一个实例,很有可能。您从失败的断言中获得的错误消息应该会告诉您。阅读。
"s", for example is an instance of java.lang.Object, but its class is not java.lang.Object, it's java.lang.String.
"s",比如是java.lang.Object的一个实例,但是它的类不是java.lang.Object,而是java.lang.String。
回答by Rohit Jain
Because expectedKey.getClass()gives the Classobject of runtime type of the expectedKey, which may be different from Keyclass.
因为expectedKey.getClass()给出了Class运行时类型的对象expectedKey,可能与Key类不同。
However, with instanceof, even if expectedKeyruntime type is some subclass of Keyclass, the result will be true, because an instance of subclass, is also an instanceofthe super class.
但是,使用instanceof,即使expectedKey运行时类型是类的某个子Key类,结果也会是true,因为子类的实例也是instanceof超类。
回答by Karibasappa G C
expectedKeyis a subclass of Keyclass as i can see
expectedKeyKey如我所见,是类的子类
assertTrue(expectedKey instanceof Key)returning true since expectedKey's class is a subclass of Key class
assertTrue(expectedKey instanceof Key)返回 true,因为 expectedKey 的类是 Key 类的子类
Object.getClassreturns the complete class name of that object at run time and hence expectedKey.getClassoutputs ->ExpectedClassand Key.getClassoutputs Key class itselfand
assertEqualslooks for comparison becomes in your case as below
assertEquals(Key,ExpectedKey)and both are different
Object.getClass返回该对象的完整的类名在运行时间,从而expectedKey.getClass输出- >ExpectedClass和Key.getClass输出Key class itself以及
assertEquals外观比较在你的情况变得如下
assertEquals(Key,ExpectedKey)两者是不同的
hence it returns false
因此它返回false
回答by Stefan Birkner
There's a difference in handling null, too. The assertEqualsthrows a NullPointerExeptionwhereas the assertTruesimply fails.
处理上null也有区别。在assertEquals抛出一个NullPointerExeption,而assertTrue只是失败。

