Home » Java » assertTrue with "instanceof" vs assertEquals

assertTrue with "instanceof" vs assertEquals

Posted by: admin December 28, 2021 Leave a comment


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?


Because expectedKey is an instance of a subclass of Key, most probably. The error message you get from the failed assertion should tell you. Read it.

"s", for example is an instance of java.lang.Object, but its class is not java.lang.Object, it’s java.lang.String.


Because expectedKey.getClass() gives the Class object of runtime type of the expectedKey, which may be different from Key class.

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.


expectedKey is a subclass of Key class as i can see

assertTrue(expectedKey instanceof Key) returning true since expectedKey’s class is a subclass of Key class

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
assertEquals looks for comparison becomes in your case as below
assertEquals(Key,ExpectedKey) and both are different

hence it returns false


There’s a difference in handling null, too. The assertEquals throws a NullPointerExeption whereas the assertTrue simply fails.