Assert an object is a specific type

后端 未结 4 580
滥情空心
滥情空心 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:18

    Solution for JUnit 5 for Kotlin!

    Example for Hamcrest:

    import org.hamcrest.CoreMatchers
    import org.hamcrest.MatcherAssert
    import org.junit.jupiter.api.Test
    
    class HamcrestAssertionDemo {
    
        @Test
        fun assertWithHamcrestMatcher() {
            val subClass = SubClass()
            MatcherAssert.assertThat(subClass, CoreMatchers.instanceOf(BaseClass::class.java))
        }
    
    }
    

    Example for AssertJ:

    import org.assertj.core.api.Assertions.assertThat
    import org.junit.jupiter.api.Test
    
    class AssertJDemo {
    
        @Test
        fun assertWithAssertJ() {
            val subClass = SubClass()
            assertThat(subClass).isInstanceOf(BaseClass::class.java)
        }
    
    }
    

提交回复
热议问题