Last Updated on 08 July 2024   |   Print Email
When writing code for unit tests using JUnit, you may need to check if an object is of a specific class type. In other words, your tests need to assert that an object is instance of a specific class. In this post, I’d like to share with you 3 ways for such purpose in Java and JUnit.
1. Using Java’s assert statement with instanceof operator
This is the simplest way to verify whether an object is of a specified type or not, using pure Java programming language (assert and instanceof keywords), as shown below:
Very simple, right? In this example, the test will pass if the object objis of type Student class.
2. Using JUnit’s assertTrue() method
The second way to test if an object is an instance of a specific class is using the assertTrue() method provided by the Assertions class in JUnit. The following example shows you how:
This test will pass if the given object obj is not an instance of Student class.
3. Using JUnit’s assertInstanceOf() Method
Since JUnit 5.10 or later, you can use the assertInstanceOf() method provided in the Assertions class, for more readability. The following example shows you how:
As you can see, this method requires 2 parameters: the first one is the expected class type, and the second one is the actual object. If you have static import for the assertInstanceOf() method, the code could be shorter like this:
So far you have learned 3 different ways which can be used to assert that an object is of a specific type in Java and JUnit. Which one to use depends on your taste: using assert and instanceof seems to be the easiest way, however using the assertInstanceOf() method seems to be more readable.
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.
Comments