0
# Type and Null Assertions
1
2
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.
3
4
## Capabilities
5
6
### assertIs
7
8
Asserts that a value is of a specific type and provides smart cast to that type.
9
10
```kotlin { .api }
11
/**
12
* Asserts that value is of type T and returns it cast to T.
13
* Provides smart cast for subsequent usage.
14
* @param value The value to check and cast
15
* @param message Optional message to show if assertion fails
16
* @return The value cast to type T
17
* @throws AssertionError if value is not of type T
18
* @since Kotlin 1.5
19
*/
20
inline fun <reified T> assertIs(value: Any?, message: String? = null): T
21
```
22
23
**Usage Examples:**
24
25
```kotlin
26
import kotlin.test.assertIs
27
28
@Test
29
fun testTypeAssertions() {
30
// Basic type checking with smart cast
31
val anyValue: Any = "Hello World"
32
val stringValue = assertIs<String>(anyValue)
33
assertEquals(11, stringValue.length) // Smart cast allows string operations
34
35
// Custom message
36
val result = parseValue("42")
37
val intResult = assertIs<Int>(result, "Parsed value should be an integer")
38
assertTrue(intResult > 0)
39
40
// Nullable type checking
41
val nullableValue: Any? = createOptionalValue()
42
if (nullableValue != null) {
43
val nonNullValue = assertIs<String>(nullableValue, "Value should be a string")
44
assertTrue(nonNullValue.isNotEmpty())
45
}
46
47
// Collection type checking
48
val collection: Any = listOf(1, 2, 3)
49
val list = assertIs<List<Int>>(collection)
50
assertEquals(3, list.size)
51
}
52
```
53
54
### assertIsNot
55
56
Asserts that a value is not of a specific type.
57
58
```kotlin { .api }
59
/**
60
* Asserts that value is not of type T.
61
* @param value The value to check
62
* @param message Optional message to show if assertion fails
63
* @throws AssertionError if value is of type T
64
* @since Kotlin 1.5
65
*/
66
inline fun <reified T> assertIsNot(value: Any?, message: String? = null)
67
```
68
69
**Usage Examples:**
70
71
```kotlin
72
import kotlin.test.assertIsNot
73
74
@Test
75
fun testTypeRejection() {
76
// Basic type rejection
77
val anyValue: Any = 42
78
assertIsNot<String>(anyValue, "Integer should not be a string")
79
80
// Ensuring wrong type parsing doesn't occur
81
val parseResult = tryParseAsNumber("hello")
82
assertIsNot<Number>(parseResult, "Non-numeric string should not parse as number")
83
84
// Polymorphism validation
85
val shape: Shape = Circle(5.0)
86
assertIsNot<Rectangle>(shape, "Circle should not be a rectangle")
87
88
// Null checking with type rejection
89
val nullValue: Any? = null
90
assertIsNot<String>(nullValue, "Null should not be treated as string")
91
}
92
```
93
94
### assertNotNull
95
96
Asserts that a value is not null and provides smart cast to non-null type.
97
98
```kotlin { .api }
99
/**
100
* Asserts that actual is not null and returns it as non-nullable type.
101
* Provides smart cast for subsequent usage.
102
* @param actual The nullable value to check
103
* @param message Optional message to show if assertion fails
104
* @return The value cast to non-null type T
105
* @throws AssertionError if actual is null
106
*/
107
fun <T : Any> assertNotNull(actual: T?, message: String? = null): T
108
109
/**
110
* Asserts that actual is not null and executes the given block with the non-null value.
111
* @param actual The nullable value to check
112
* @param message Optional message to show if assertion fails
113
* @param block Lambda to execute with the non-null value
114
* @return The result of executing the block
115
* @throws AssertionError if actual is null
116
*/
117
fun <T : Any, R> assertNotNull(actual: T?, message: String? = null, block: (T) -> R): R
118
```
119
120
**Usage Examples:**
121
122
```kotlin
123
import kotlin.test.assertNotNull
124
125
@Test
126
fun testNotNullAssertions() {
127
// Basic null checking with smart cast
128
val nullableString: String? = getString()
129
val nonNullString = assertNotNull(nullableString, "String should not be null")
130
assertEquals(5, nonNullString.length) // Smart cast allows string operations
131
132
// Block execution with non-null value
133
val nullableUser: User? = findUser("alice")
134
assertNotNull(nullableUser, "User should be found") { user ->
135
assertTrue(user.isActive)
136
assertEquals("alice", user.username.lowercase())
137
}
138
139
// API response validation
140
val response: ApiResponse? = makeApiCall()
141
val validResponse = assertNotNull(response, "API should return a response")
142
assertTrue(validResponse.isSuccess)
143
144
// Collection element validation
145
val list = listOf("a", "b", null, "d")
146
val thirdElement = list[2]
147
// This would fail: assertNotNull(thirdElement, "Third element should not be null")
148
149
val firstElement = list[0]
150
assertNotNull(firstElement, "First element should not be null")
151
assertEquals("a", firstElement)
152
}
153
```
154
155
### assertNull
156
157
Asserts that a value is null.
158
159
```kotlin { .api }
160
/**
161
* Asserts that actual is null.
162
* @param actual The value to check for nullness
163
* @param message Optional message to show if assertion fails
164
* @throws AssertionError if actual is not null
165
*/
166
fun assertNull(actual: Any?, message: String? = null)
167
```
168
169
**Usage Examples:**
170
171
```kotlin
172
import kotlin.test.assertNull
173
174
@Test
175
fun testNullAssertions() {
176
// Basic null validation
177
val result: String? = findOptionalValue("nonexistent")
178
assertNull(result, "Should return null for nonexistent values")
179
180
// API failure scenarios
181
val failedResponse: Response? = makeFailingApiCall()
182
assertNull(failedResponse, "Failed API call should return null")
183
184
// Optional parameter validation
185
val config = Configuration(
186
host = "localhost",
187
port = 8080,
188
ssl = null // Optional parameter
189
)
190
assertNull(config.ssl, "SSL should be null when not configured")
191
192
// Cache miss validation
193
val cachedValue = cache.get("missing-key")
194
assertNull(cachedValue, "Cache should return null for missing keys")
195
196
// Cleanup validation
197
var resource: Resource? = acquireResource()
198
resource.close()
199
resource = null
200
assertNull(resource, "Resource should be null after cleanup")
201
}
202
```
203
204
## Error Handling
205
206
Type and null assertion functions will throw an `AssertionError` when conditions fail:
207
208
- **assertIs**: Throws when value is not of the expected type
209
- **assertIsNot**: Throws when value is of the rejected type
210
- **assertNotNull**: Throws when value is null
211
- **assertNull**: Throws when value is not null
212
213
Error messages include type information and actual values for debugging:
214
215
```kotlin
216
// This will throw: AssertionError: Expected value to be kotlin.String, actual was kotlin.Int
217
assertIs<String>(42)
218
219
// This will throw: AssertionError: Expected value to be not null.
220
assertNotNull(null, "Value should not be null")
221
222
// This will throw: AssertionError: Expected null, actual <User(name=Alice)>
223
assertNull(User("Alice"))
224
```
225
226
## Smart Cast Benefits
227
228
The `assertIs` and `assertNotNull` functions provide Kotlin smart cast capabilities, eliminating the need for additional casting:
229
230
```kotlin
231
val anyValue: Any = "Hello"
232
val stringValue = assertIs<String>(anyValue)
233
// No additional casting needed - stringValue is now String type
234
println(stringValue.uppercase()) // String methods available directly
235
236
val nullableInt: Int? = 42
237
val nonNullInt = assertNotNull(nullableInt)
238
// No additional casting needed - nonNullInt is now Int type
239
println(nonNullInt + 10) // Int operations available directly
240
```