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:

@Test
public void test() {

	Object obj = classUnderTest.foo();
	
	assert (obj instanceof Student);
}
Very simple, right? In this example, the test will pass if the object obj is 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:

@Test
public void test() {

	Object obj = classUnderTest.foo();
	
	Assertions.assertTrue(obj instanceof Student);
}
If you use static import for the assertTrue() method, the code can be shorter like this:

@Test
public void test() {

	Object obj = classUnderTest.foo();
	
	assertTrue(obj instanceof Student);
}
In case you want to do the reverse, i.e. assert that an object is not of a specific type, use the assertFalse() method. For example:

@Test
public void test() {

	Object obj = classUnderTest.foo();
	
	Assertions.assertFalse(obj instanceof Student);
}
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:

@Test
public void test() {

	Object obj = classUnderTest.foo();
	
	Assertions.assertInstanceOf(Student.class, obj);
}
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:

@Test
public void test() {

	Object obj = classUnderTest.foo();
	
	assertInstanceOf(Student.class, obj);
}
  

Conclusion:

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.

 

References:

 

Other JUnit Tutorials:


About the Author:

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.



Add comment