Assert an object is a specific type

后端 未结 4 563
滥情空心
滥情空心 2020-12-02 07:35

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 Obje

4条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-02 08:21

    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));
        }
    }
    

提交回复
热议问题