AssertInstanceOf Example

In this post under JUnit 5, I will show with example, the purpose and how to use “assertInstanceOf” method. The assertInstanceOf method from JUnit 5 can be used to verify whether an object is actually an instance of the specified class or not. If an object is actually an instance of passed in Class, then the assert method passes or else fails. Below is the complete main class code showing how to use it.

Main Class


1  package package9;
2  
3  import static org.junit.jupiter.api.Assertions.assertInstanceOf;
4  
5  import java.util.Date;
6  import org.junit.jupiter.api.Test;
7  
8  public class CalculatorTest {
9      @Test
10     public void testInstanceOf() {
11         Calculator calculator = new Calculator();
12         assertInstanceOf(Calculator.class, calculator);
13         Date date = new Date();
14         assertInstanceOf(Calculator.class, date);
15     }
16 }
17 
18 class Calculator {
19     
20 }

In the above code, we have created a “Calculator” class for testing purposes.

In the test class, we have added a method “testInstanceOf” which will verify whether an object is an instance of “Calculator” class or not.

At line 11, we create an instance of “Calculator” class.

At line 12, we use “assertInstanceOf” method passing the “Calculator” class object and an object. Since the passed in object is actually an instance of “Calculator” class, the assert passes successfully.

At line 13, we create an instance of “Date” class. At line 14, we again call “assertInstanceOf” method passing the “Calculator” class object and an instance of “Date” class. Since the passed in object is not an instance “Calculator”, the assert fails.

In this way, we can check whether an object is an instance of a Class or not.

Leave a Reply