CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-org-jetbrains-kotlin--kotlin-test

Multiplatform testing framework providing unified API for writing tests across all Kotlin platforms with assertions and test annotations.

Pending
Overview
Eval results
Files

type-null-assertions.mddocs/

Type and Null Assertions

Assertions for type checking and null safety validation, essential for ensuring type safety and handling nullable values in Kotlin tests.

Capabilities

Type Assertions

assertIs Function

Asserts that a value is of a specific type and performs a smart cast.

/**
 * Asserts that value is of type T and returns it cast to T
 * @param value - Value to check and cast
 * @param message - Optional custom failure message
 * @return The value cast to type T
 */
inline fun <reified T> assertIs(value: Any?, message: String? = null): T

Usage Examples:

import kotlin.test.*

@Test
fun testTypeChecking() {
    val obj: Any = "hello world"
    
    // Assert type and get typed reference
    val str = assertIs<String>(obj)
    assertEquals(11, str.length)
    
    // With custom message
    val number: Any = 42
    val int = assertIs<Int>(number, "Value should be an integer")
    assertTrue(int > 0)
    
    // Works with nullable types
    val nullableValue: Any? = "test"
    val result = assertIs<String>(nullableValue)
    assertEquals("test", result)
}

@Test
fun testPolymorphism() {
    val shapes: List<Any> = listOf(
        Circle(5.0),
        Rectangle(10.0, 20.0),
        "not a shape"
    )
    
    shapes.forEach { shape ->
        when {
            shape is Circle -> {
                val circle = assertIs<Circle>(shape)
                assertTrue(circle.radius > 0)
            }
            shape is Rectangle -> {
                val rect = assertIs<Rectangle>(shape)
                assertTrue(rect.width > 0 && rect.height > 0)
            }
        }
    }
}

assertIsNot Function

Asserts that a value is not of a specific type.

/**
 * Asserts that value is not of type T
 * @param value - Value to check
 * @param message - Optional custom failure message
 */
inline fun <reified T> assertIsNot(value: Any?, message: String? = null)

Usage Examples:

@Test
fun testTypeRejection() {
    val obj: Any = 42
    
    // Assert it's not a string
    assertIsNot<String>(obj)
    assertIsNot<List<*>>(obj, "Should not be a list")
    
    // Test with null
    val nullValue: Any? = null
    assertIsNot<String>(nullValue, "Null should not be considered a String")
}

@Test
fun testInputValidation() {
    fun processInput(input: Any) {
        assertIsNot<Collection<*>>(input, "Input should not be a collection")
        // Safe to process as non-collection
    }
    
    processInput("string")
    processInput(42)
    processInput(true)
}

Null Assertions

assertNotNull Function

Asserts that a value is not null and returns it as a non-null type.

/**
 * Asserts that the actual value is not null
 * @param actual - Nullable value to check
 * @param message - Optional custom failure message
 * @return The value cast to non-null type T
 */
fun <T : Any> assertNotNull(actual: T?, message: String? = null): T

/**
 * Asserts that the actual value is not null and processes it with a block
 * @param actual - Nullable value to check
 * @param message - Optional custom failure message
 * @param block - Function to execute with the non-null value
 */
inline fun <T : Any, R> assertNotNull(actual: T?, message: String? = null, block: (T) -> R)

Usage Examples:

@Test
fun testNotNullValues() {
    val name: String? = getName()
    
    // Assert not null and get non-null reference
    val safeName = assertNotNull(name, "Name should not be null")
    assertTrue(safeName.isNotEmpty())
    
    // Using the block form
    val user: User? = findUser("john")
    assertNotNull(user, "User should be found") { u ->
        assertEquals("john", u.username)
        assertTrue(u.isActive)
    }
}

@Test
fun testDatabaseResults() {
    val connection: DatabaseConnection? = getConnection()
    assertNotNull(connection, "Database connection should be established")
    
    val result: QueryResult? = connection.executeQuery("SELECT * FROM users")
    assertNotNull(result, "Query should return results") { queryResult ->
        assertTrue(queryResult.hasRows())
        assertNotNull(queryResult.getFirstRow())
    }
}

@Test
fun testNullableChaining() {
    val data: String? = loadData()
    
    // Chain operations after null check
    assertNotNull(data) { safeData ->
        val processed = safeData.uppercase().trim()
        assertTrue(processed.isNotEmpty())
        assertEquals("EXPECTED", processed)
    }
}

assertNull Function

Asserts that a value is null.

/**
 * Asserts that the actual value is null
 * @param actual - Value to check for nullness
 * @param message - Optional custom failure message
 */
fun assertNull(actual: Any?, message: String? = null)

Usage Examples:

@Test
fun testNullValues() {
    val emptyResult: String? = findNonExistentItem()
    assertNull(emptyResult, "Should return null for non-existent item")
    
    // Test cleanup
    var resource: Resource? = createResource()
    resource.close()
    resource = null
    assertNull(resource, "Resource should be null after cleanup")
}

@Test
fun testOptionalOperations() {
    val cache = mutableMapOf<String, String>()
    
    // Key doesn't exist
    val missing = cache["nonexistent"]
    assertNull(missing, "Non-existent key should return null")
    
    // After removal
    cache["key"] = "value"
    cache.remove("key")
    assertNull(cache["key"], "Removed key should return null")
}

@Test
fun testNullableTypes() {
    fun maybeProcess(input: String?): String? {
        return if (input?.isNotEmpty() == true) input.uppercase() else null
    }
    
    // Test null input
    assertNull(maybeProcess(null))
    assertNull(maybeProcess(""))
    
    // Test valid input
    val result = maybeProcess("hello")
    assertNotNull(result)
    assertEquals("HELLO", result)
}

Advanced Usage Patterns

Type-Safe Testing with Generics

@Test
fun testGenericTypes() {
    val list: Any = listOf("a", "b", "c")
    
    // Assert specific generic type
    val stringList = assertIs<List<*>>(list)
    assertEquals(3, stringList.size)
    
    // More specific assertion
    val strings = assertIs<List<String>>(list)
    assertTrue(strings.all { it is String })
}

Nullable Reference Chains

@Test
fun testNullableChains() {
    data class User(val profile: Profile?)
    data class Profile(val email: String?)
    
    val user: User? = getUser()
    assertNotNull(user, "User should exist") { u ->
        assertNotNull(u.profile, "User should have profile") { profile ->
            assertNotNull(profile.email, "Profile should have email") { email ->
                assertTrue(email.contains("@"))
            }
        }
    }
}

Error Handling with Type Checks

@Test
fun testErrorHandling() {
    val response: Any = makeApiCall()
    
    when {
        response is ErrorResponse -> {
            val error = assertIs<ErrorResponse>(response)
            assertTrue(error.code > 0)
            assertNotNull(error.message)
        }
        response is SuccessResponse -> {
            val success = assertIs<SuccessResponse>(response)
            assertNotNull(success.data)
        }
        else -> {
            fail("Unexpected response type: ${response::class}")
        }
    }
}

Combining Type and Null Assertions

@Test
fun testCombinedAssertions() {
    val result: Any? = processInput("test")
    
    // First check it's not null
    assertNotNull(result, "Processing should return a value")
    
    // Then check its type
    val stringResult = assertIs<String>(result, "Result should be a string")
    
    // Finally verify content
    assertTrue(stringResult.isNotEmpty())
    assertEquals("PROCESSED: test", stringResult)
}

Install with Tessl CLI

npx tessl i tessl/maven-org-jetbrains-kotlin--kotlin-test

docs

annotations.md

asserter.md

basic-assertions.md

collection-assertions.md

exception-testing.md

index.md

type-null-assertions.md

tile.json