Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

assertTrue with "instanceof" vs assertEquals

Tags:

java

junit

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?

like image 357
quarks Avatar asked Apr 25 '14 08:04

quarks


People also ask

What is the difference between assertEquals and assertSame?

assertEquals() Asserts that two objects are equal. assertSame() Asserts that two objects refer to the same object. the assertEquals should pass and assertSame should fail, as the value of both classes are equal but they have different reference location.

What does the assertTrue () method do?

assertTrue is used to verify if a given Boolean condition is true. This assertion returns true if the specified condition passes, if not, then an assertion error is thrown.

What is the method assertEquals () used for?

assertEquals. Asserts that two object arrays are equal. If they are not, an AssertionError is thrown with the given message. If expecteds and actuals are null , they are considered equal.

What is assertTrue and assertFalse?

In assertTrue, you are asserting that the expression is true. If it is not, then it will display the message and the assertion will fail. In assertFalse, you are asserting that an expression evaluates to false. If it is not, then the message is displayed and the assertion fails.


2 Answers

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.

like image 23
Rohit Jain Avatar answered Oct 04 '22 10:10

Rohit Jain


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.

like image 96
JB Nizet Avatar answered Oct 04 '22 10:10

JB Nizet