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 expectedKey
is 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 Class
object of runtime type of the expectedKey
, which may be different from Key
class.
因为expectedKey.getClass()
给出了Class
运行时类型的对象expectedKey
,可能与Key
类不同。
However, with instanceof
, even if expectedKey
runtime type is some subclass of Key
class, the result will be true
, because an instance of subclass, is also an instanceof
the super class.
但是,使用instanceof
,即使expectedKey
运行时类型是类的某个子Key
类,结果也会是true
,因为子类的实例也是instanceof
超类。
回答by Karibasappa G C
expectedKey
is a subclass of Key
class as i can see
expectedKey
Key
如我所见,是类的子类
assertTrue(expectedKey instanceof Key)
returning true since expectedKey's class is a subclass of Key class
assertTrue(expectedKey instanceof Key)
返回 true,因为 expectedKey 的类是 Key 类的子类
Object.getClass
returns the complete class name of that object at run time and hence expectedKey.getClass
outputs ->ExpectedClass
and Key.getClass
outputs Key class itself
and
assertEquals
looks 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 assertEquals
throws a NullPointerExeption
whereas the assertTrue
simply fails.
处理上null
也有区别。在assertEquals
抛出一个NullPointerExeption
,而assertTrue
只是失败。