CtrlK
BlogDocsLog inGet started
Tessl Logo

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

Common test assertions and utilities for Kotlin multiplatform projects

Pending
Overview
Eval results
Files

type-null-assertions.mddocs/

Type and Null Assertions

Type checking and null safety assertions with smart cast support and contract-based APIs. These functions provide runtime type validation and null safety guarantees essential for robust test validation in Kotlin's type system.

Capabilities

assertIs

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

/**
 * Asserts that value is of type T and returns it cast to T.
 * Provides smart cast for subsequent usage.
 * @param value The value to check and cast
 * @param message Optional message to show if assertion fails
 * @return The value cast to type T
 * @throws AssertionError if value is not of type T
 * @since Kotlin 1.5
 */
inline fun <reified T> assertIs(value: Any?, message: String? = null): T

Usage Examples:

import kotlin.test.assertIs

@Test
fun testTypeAssertions() {
    // Basic type checking with smart cast
    val anyValue: Any = "Hello World"
    val stringValue = assertIs<String>(anyValue)
    assertEquals(11, stringValue.length) // Smart cast allows string operations
    
    // Custom message
    val result = parseValue("42")
    val intResult = assertIs<Int>(result, "Parsed value should be an integer")
    assertTrue(intResult > 0)
    
    // Nullable type checking
    val nullableValue: Any? = createOptionalValue()
    if (nullableValue != null) {
        val nonNullValue = assertIs<String>(nullableValue, "Value should be a string")
        assertTrue(nonNullValue.isNotEmpty())
    }
    
    // Collection type checking
    val collection: Any = listOf(1, 2, 3)
    val list = assertIs<List<Int>>(collection)
    assertEquals(3, list.size)
}

assertIsNot

Asserts that a value is not of a specific type.

/**
 * Asserts that value is not of type T.
 * @param value The value to check
 * @param message Optional message to show if assertion fails
 * @throws AssertionError if value is of type T
 * @since Kotlin 1.5
 */
inline fun <reified T> assertIsNot(value: Any?, message: String? = null)

Usage Examples:

import kotlin.test.assertIsNot

@Test
fun testTypeRejection() {
    // Basic type rejection
    val anyValue: Any = 42
    assertIsNot<String>(anyValue, "Integer should not be a string")
    
    // Ensuring wrong type parsing doesn't occur
    val parseResult = tryParseAsNumber("hello")
    assertIsNot<Number>(parseResult, "Non-numeric string should not parse as number")
    
    // Polymorphism validation
    val shape: Shape = Circle(5.0)
    assertIsNot<Rectangle>(shape, "Circle should not be a rectangle")
    
    // Null checking with type rejection
    val nullValue: Any? = null
    assertIsNot<String>(nullValue, "Null should not be treated as string")
}

assertNotNull

Asserts that a value is not null and provides smart cast to non-null type.

/**
 * Asserts that actual is not null and returns it as non-nullable type.
 * Provides smart cast for subsequent usage.
 * @param actual The nullable value to check
 * @param message Optional message to show if assertion fails
 * @return The value cast to non-null type T
 * @throws AssertionError if actual is null
 */
fun <T : Any> assertNotNull(actual: T?, message: String? = null): T

/**
 * Asserts that actual is not null and executes the given block with the non-null value.
 * @param actual The nullable value to check
 * @param message Optional message to show if assertion fails
 * @param block Lambda to execute with the non-null value
 * @return The result of executing the block
 * @throws AssertionError if actual is null
 */
fun <T : Any, R> assertNotNull(actual: T?, message: String? = null, block: (T) -> R): R

Usage Examples:

import kotlin.test.assertNotNull

@Test
fun testNotNullAssertions() {
    // Basic null checking with smart cast
    val nullableString: String? = getString()
    val nonNullString = assertNotNull(nullableString, "String should not be null")
    assertEquals(5, nonNullString.length) // Smart cast allows string operations
    
    // Block execution with non-null value
    val nullableUser: User? = findUser("alice")
    assertNotNull(nullableUser, "User should be found") { user ->
        assertTrue(user.isActive)
        assertEquals("alice", user.username.lowercase())
    }
    
    // API response validation
    val response: ApiResponse? = makeApiCall()
    val validResponse = assertNotNull(response, "API should return a response")
    assertTrue(validResponse.isSuccess)
    
    // Collection element validation
    val list = listOf("a", "b", null, "d")
    val thirdElement = list[2]
    // This would fail: assertNotNull(thirdElement, "Third element should not be null")
    
    val firstElement = list[0]
    assertNotNull(firstElement, "First element should not be null")
    assertEquals("a", firstElement)
}

assertNull

Asserts that a value is null.

/**
 * Asserts that actual is null.
 * @param actual The value to check for nullness
 * @param message Optional message to show if assertion fails
 * @throws AssertionError if actual is not null
 */
fun assertNull(actual: Any?, message: String? = null)

Usage Examples:

import kotlin.test.assertNull

@Test
fun testNullAssertions() {
    // Basic null validation
    val result: String? = findOptionalValue("nonexistent")
    assertNull(result, "Should return null for nonexistent values")
    
    // API failure scenarios
    val failedResponse: Response? = makeFailingApiCall()
    assertNull(failedResponse, "Failed API call should return null")
    
    // Optional parameter validation
    val config = Configuration(
        host = "localhost",
        port = 8080,
        ssl = null  // Optional parameter
    )
    assertNull(config.ssl, "SSL should be null when not configured")
    
    // Cache miss validation
    val cachedValue = cache.get("missing-key")
    assertNull(cachedValue, "Cache should return null for missing keys")
    
    // Cleanup validation
    var resource: Resource? = acquireResource()
    resource.close()
    resource = null
    assertNull(resource, "Resource should be null after cleanup")
}

Error Handling

Type and null assertion functions will throw an AssertionError when conditions fail:

  • assertIs: Throws when value is not of the expected type
  • assertIsNot: Throws when value is of the rejected type
  • assertNotNull: Throws when value is null
  • assertNull: Throws when value is not null

Error messages include type information and actual values for debugging:

// This will throw: AssertionError: Expected value to be kotlin.String, actual was kotlin.Int
assertIs<String>(42)

// This will throw: AssertionError: Expected value to be not null.
assertNotNull(null, "Value should not be null")

// This will throw: AssertionError: Expected null, actual <User(name=Alice)>
assertNull(User("Alice"))

Smart Cast Benefits

The assertIs and assertNotNull functions provide Kotlin smart cast capabilities, eliminating the need for additional casting:

val anyValue: Any = "Hello"
val stringValue = assertIs<String>(anyValue)
// No additional casting needed - stringValue is now String type
println(stringValue.uppercase()) // String methods available directly

val nullableInt: Int? = 42
val nonNullInt = assertNotNull(nullableInt)
// No additional casting needed - nonNullInt is now Int type
println(nonNullInt + 10) // Int operations available directly

Install with Tessl CLI

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

docs

boolean-assertions.md

collection-assertions.md

equality-assertions.md

exception-testing.md

framework-integration.md

index.md

test-annotations.md

test-utilities.md

type-null-assertions.md

tile.json