How would you write assertThat(foo, instanceOf(Bar.class)) with Kotlin?

Seems that it does not like the .class

如果可能的话,我想要一个比assertTrue(foo is Bar)更"精确"的断言.

推荐答案

Bar::class返回KClass的实例,这是相当于Java Class的Kotlin.

instanceOf方法需要Class个实例,而不是KClass个,所以您必须使用Bar::class.java来转换它.

所以你的断言应该是这样的:

assertThat(foo, instanceOf(Bar::class.java))

More info about Java interop you can find here.

Also you can have a look at Hamkrest library which may add more fluency to your assertions:

assert.that(foo, isA<Bar>())

Kotlin相关问答推荐

在Kotlin中处理结果的高阶函数

API迁移到Spring Boot 3后,Spring Security无法工作

Kotlin是否针对范围和进度优化sum()?

Kotlin Poet 的导入不明确

Kotlin 获取继承类的默认 hashCode 实现

Kotlin supervisorScope 即使包裹在 try catch 中也会失败

多个不同的指针输入

伴随对象在变量更改时更改它的值

OnClickListener 未在 ConstraintLayout 上触发

有没有办法重用 Job 实例?

DatabaseManager_Impl 不是抽象的,不会覆盖 RoomDatabase 中的抽象方法 clearAllTables()

如何用 kotlin 打包 List

Kotlin JVM 和 Kotlin Native 有什么区别?

Kapt不适用于Android Studio 3.0中的AutoValue

如何将 Kotlin 日期中的字符串或时间戳格式化为指定的首选格式?

Kotlin通过映射委托属性,如果映射中不存在,则抛出NoTouchElementException

使用范围的稀疏sparse值列表

保存对象时未填充 Spring Boot JPA@CreatedDate @LastModifiedDate

使用 rxbinding 时我应该取消订阅吗?

Kotlin var lazy init