Since Kotlin 1.5 there is a nice solution included in kotlin-test:
assertIs<TypeExpected>(value)
This will not only assert that value
is of type TypeExpected
, it will also smart cast value
, so that you can access all methods of TypeExpected
. Just include the dependency, e.g:
testImplementation("org.jetbrains.kotlin:kotlin-test-junit5:1.7.10")
And you can do stuff like this
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertIs
class AssertIsTests {
@Test
fun `test for list`() {
val list = Collector.List.collect(1, 1, 2, 2, 3)
assertEquals(5, list.size)
// assertEquals(1, list[0]) won't compile: list is of type Collection<Int> which doesn't support []
assertIs<List<Int>>(list) // from now on list is of type List<Int>!
assertEquals(4, list.indexOf(3)) // now there are all list methods
assertEquals(1, list[0]) // including indexed getters
}
@Test
fun `test for set`() {
val set = Collector.Set.collect(1, 1, 2, 2, 3)
assertEquals(3, set.size) // Set with duplicates removed
assertIs<Set<Int>>(set) // from now on set is of Type Set<Int>
}
}
enum class Collector {
List {
override fun collect(vararg args: Int) = args.toList()
},
Set {
override fun collect(vararg args: Int) = args.toSet()
};
abstract fun collect(vararg args: Int): Collection<Int>
}
assertTrue { value is ExpectedType }
– JaquelynjaquenettaassertTrue { value is ExpectedType }
would work, but it doesn't read fluid and the exception message doesn't reveal any information of the actual exception, in case of an failure. – Keratose