kotlin-test: add assertIs and assertNotIs assertions KT-45296

This commit is contained in:
Ben Asher
2020-08-15 11:06:22 -07:00
committed by Ilya Gorbunov
parent 542518f290
commit 3a0219d84c
3 changed files with 54 additions and 0 deletions

View File

@@ -17,6 +17,7 @@ import kotlin.internal.*
import kotlin.jvm.JvmName
import kotlin.native.concurrent.ThreadLocal
import kotlin.reflect.KClass
import kotlin.reflect.typeOf
/**
* Current adapter providing assertion implementations
@@ -76,6 +77,31 @@ fun <@OnlyInputTypes T> assertNotSame(illegal: T, actual: T, message: String? =
asserter.assertNotSame(message, illegal, actual)
}
/**
* Asserts that [value] is of type [T], with an optional [message].
*
* Note that due to type erasure the type check may be partial (e.g. assertIs<List<String>>(value)
* only checks for the class being [List] and not the type of its elements because it's erased).
*/
@SinceKotlin("1.5")
@InlineOnly
inline fun <reified T> assertIs(value: Any?, message: String? = null) {
contract { returns() implies (value is T) }
asserter.assertTrue({ messagePrefix(message) + "Expected value to be of type <${typeOf<T>()}>, actual <${value?.let { it::class }}>." }, value is T)
}
/**
* Asserts that [value] is not of type [T], with an optional [message].
*
* Note that due to type erasure the type check may be partial (e.g. assertNotIs<List<String>>(value)
* only checks for the class being [List] and not the type of its elements because it's erased).
*/
@SinceKotlin("1.5")
@InlineOnly
inline fun <reified T> assertNotIs(value: Any?, message: String? = null) {
asserter.assertFalse({ messagePrefix(message) + "Expected value to not be of type <${typeOf<T>()}>" }, value is T)
}
/** Asserts that the [actual] value is not `null`, with an optional [message]. */
fun <T : Any> assertNotNull(actual: T?, message: String? = null): T {
contract { returns() implies (actual != null) }

View File

@@ -5,6 +5,7 @@
package kotlin.test
@PublishedApi // called from inline assert functions
internal fun messagePrefix(message: String?) = if (message == null) "" else "$message. "
internal expect fun lookupAsserter(): Asserter

View File

@@ -205,6 +205,33 @@ class BasicAssertionsTest {
fun testExpectFails() {
checkFailedAssertion { expect(1) { 2 } }
}
@Test
fun testAssertIs() {
val s: Any = "test"
assertIs<String>(s)
assertEquals(4, s.length)
}
@Test
fun testAssertIsFails() {
val error = checkFailedAssertion { assertIs<Int>("test") }
assertTrue(error.message.startsWith("Expected value to be of type"))
assertTrue(error.message.contains("Int"))
assertTrue(error.message.contains("String"))
}
@Test
fun testAssertNotIs() {
assertNotIs<Int>("test")
}
@Test
fun testAssertNotIsFails() {
val error = checkFailedAssertion { assertNotIs<Int>(1) }
assertTrue(error.message.startsWith("Expected value to not be of type"))
assertTrue(error.message.contains("Int"))
}
}