Search code examples
javaunit-testingjunit

Assert an object is a specific type


Is it possible in JUnit to assert an object is an instance of a class? For various reasons I have an object in my test that I want to check the type of. Is it a type of Object1 or a type of Object2?

Currently I have:

assertTrue(myObject instanceof Object1);
assertTrue(myObject instanceof Object2);

This works but I was wondering if there is a more expressive way of doing this.

For example something like:

assertObjectIsClass(myObject, Object1);

I could do this:

assertEquals(Object1.class, myObject.getClass());

Is there a specific assert method that allows me to test a type of an object in a more elegant, fluid manner?


Solution

  • You can use the assertThat method and the Matchers that comes with JUnit.

    Take a look at this link that describes a little bit about the JUnit Matchers.

    Example:

    public class BaseClass {
    }
    
    public class SubClass extends BaseClass {
    }
    

    Test:

    import org.junit.Test;
    
    import static org.hamcrest.CoreMatchers.instanceOf;
    import static org.junit.Assert.assertThat;
    
    /**
     * @author maba, 2012-09-13
     */
    public class InstanceOfTest {
    
        @Test
        public void testInstanceOf() {
            SubClass subClass = new SubClass();
            assertThat(subClass, instanceOf(BaseClass.class));
        }
    }