Explain Codes LogoExplain Codes Logo

Assert an object is a specific type

java
assertions
junit
assertj
Anton ShumikhinbyAnton Shumikhin·Jan 26, 2025
TLDR

To assert an object to be a specific type, use:

assert obj instanceof MyClass : "obj has a case of mistaken identity: NOT MyClass";

Or, honestly, interrogate the obj dynamically:

assert MyClass.class.isInstance(obj) : "AssertionError: I ain't MyClass, bro!";

Both deliver a punchy AssertionError if obj is not who we thought it was.

Turbocharge with assertThat and Matchers

Put the pedal to the metal in JUnit tests using Matchers and assertThat. It lets you don your Sherlock Holmes hat and investigate object types in style.

import static org.hamcrest.CoreMatchers.instanceOf; import static org.junit.Assert.assertThat; // ... @Test public void fireUpInstanceOfTest() { // Actual test, or a round of guessing game? assertThat(myObject, instanceOf(MyClass.class)); }

Replace multiple assertTrue or assertEquals statements with this one liner. Elegance? Check. Efficiency? Check. Confidence? Triple check!

JUnit 5: a bouquet with assertInstanceOf()

The assertInstanceOf() in JUnit 5 is like a rose among the thorns. It checks and returns the object in one fell swoop, saving you from casting nightmares.

import static org.junit.jupiter.api.Assertions.assertInstanceOf; // ... @Test void blazeInstanceOfTest() { // Treating objects with kindness and type-checking assertInstanceOf(MyClass.class, myObject); }

When assertJ plays the fiddle

AssertJ struts about with a fluent interface, turning assertions into romantic strolls in the park:

import static org.assertj.core.api.Assertions.assertThat; // ... @Test void sparkAssertJTypeCheck() { // Where AssertJ sings "Check Type-checked in 12 notes" assertThat(myObject).isInstanceOf(MyClass.class); }

When there are thorny edge cases, AssertJ plays the tune.

Kotlin: force of assert

Kotlin assert charms with its brevity. Typecasting in Java? Pfft! Say hello to is -

import kotlin.test.assertTrue // ... @Test fun kotlinRoastsJava() { // Swedish house mafias drop beats, Kotlin drops 'is' assertTrue(myObject is MyClass, "Not an instance of MyClass") }

To make Kotlin and JUnit play together, add AssertionsJVM.kt to your beat.

Avoid expiration dates

Just like milk, practices too can go bad. Stay vigilant and say no to deprecated methods. Because, that's how codebases rot!

Unmasking the real identity

When you need to verify the object's exact type identity, not its ancestry:

// 'Who's your daddy?' becomes 'Who exactly ARE you?' assertEquals(MyClass.class, myObject.getClass());

This ensures myObject's identity is a portrait-perfect match to MyClass, without dragging the family tree into this.