0
# Assertions
1
2
Comprehensive assertion functions for verifying test conditions across all common scenarios. These functions provide the core testing functionality for validating expected behavior in Kotlin/WASM-JS applications.
3
4
## Capabilities
5
6
### Basic Equality Assertions
7
8
Functions for testing equality between expected and actual values with support for different types and tolerance-based comparisons.
9
10
```kotlin { .api }
11
/**
12
* Asserts that expected and actual values are equal
13
* @param expected the expected value
14
* @param actual the actual value
15
* @param message the message to report on failure
16
*/
17
fun <T> assertEquals(expected: T, actual: T, message: String? = null)
18
19
/**
20
* Asserts that expected and actual Double values are equal within absolute tolerance
21
* @param expected the expected Double value
22
* @param actual the actual Double value
23
* @param absoluteTolerance the maximum allowed difference
24
* @param message the message to report on failure
25
*/
26
fun assertEquals(expected: Double, actual: Double, absoluteTolerance: Double, message: String? = null)
27
28
/**
29
* Asserts that expected and actual Float values are equal within absolute tolerance
30
* @param expected the expected Float value
31
* @param actual the actual Float value
32
* @param absoluteTolerance the maximum allowed difference
33
* @param message the message to report on failure
34
*/
35
fun assertEquals(expected: Float, actual: Float, absoluteTolerance: Float, message: String? = null)
36
37
/**
38
* Asserts that illegal and actual values are not equal
39
* @param illegal the value that actual should not equal
40
* @param actual the actual value
41
* @param message the message to report on failure
42
*/
43
fun <T> assertNotEquals(illegal: T, actual: T, message: String? = null)
44
```
45
46
**Usage Examples:**
47
48
```kotlin
49
import kotlin.test.*
50
51
class EqualityTests {
52
@Test
53
fun basicEquality() {
54
assertEquals(4, 2 + 2)
55
assertEquals("hello", "hello")
56
assertEquals(listOf(1, 2, 3), listOf(1, 2, 3))
57
}
58
59
@Test
60
fun floatingPointEquality() {
61
val result = 0.1 + 0.2
62
assertEquals(0.3, result, 0.0001) // Use tolerance for floating point
63
64
val floatResult = 0.1f + 0.2f
65
assertEquals(0.3f, floatResult, 0.0001f)
66
}
67
68
@Test
69
fun inequality() {
70
assertNotEquals(5, 3)
71
assertNotEquals("hello", "world")
72
assertNotEquals(0.3, 0.1 + 0.2, 0.00001) // Different tolerance
73
}
74
}
75
```
76
77
### Boolean Assertions
78
79
Functions for testing boolean conditions and block-based boolean expressions.
80
81
```kotlin { .api }
82
/**
83
* Asserts that the value is true
84
* @param actual the value to check
85
* @param message the message to report on failure
86
*/
87
fun assertTrue(actual: Boolean, message: String? = null)
88
89
/**
90
* Asserts that the block returns true
91
* @param message the message to report on failure
92
* @param block the block that should return true
93
*/
94
inline fun assertTrue(message: String? = null, block: () -> Boolean)
95
96
/**
97
* Asserts that the value is false
98
* @param actual the value to check
99
* @param message the message to report on failure
100
*/
101
fun assertFalse(actual: Boolean, message: String? = null)
102
103
/**
104
* Asserts that the block returns false
105
* @param message the message to report on failure
106
* @param block the block that should return false
107
*/
108
inline fun assertFalse(message: String? = null, block: () -> Boolean)
109
```
110
111
**Usage Examples:**
112
113
```kotlin
114
import kotlin.test.*
115
116
class BooleanTests {
117
@Test
118
fun booleanValues() {
119
assertTrue(5 > 3)
120
assertFalse(2 > 5)
121
assertTrue(listOf(1, 2, 3).isNotEmpty())
122
assertFalse(emptyList<Int>().isNotEmpty())
123
}
124
125
@Test
126
fun booleanBlocks() {
127
assertTrue("List should not be empty") {
128
val list = generateTestData()
129
list.isNotEmpty()
130
}
131
132
assertFalse("Should not find invalid user") {
133
val user = findUser("invalid-id")
134
user != null
135
}
136
}
137
}
138
```
139
140
### Null Assertions
141
142
Functions for testing null and non-null values with smart casting support.
143
144
```kotlin { .api }
145
/**
146
* Asserts that the value is not null and returns the non-null value
147
* @param actual the value to check
148
* @param message the message to report on failure
149
* @return the actual value cast to non-null type
150
*/
151
fun <T : Any> assertNotNull(actual: T?, message: String? = null): T
152
153
/**
154
* Asserts that the value is not null and passes it to the block
155
* @param actual the value to check
156
* @param message the message to report on failure
157
* @param block the block to execute with the non-null value
158
* @return the result of the block
159
*/
160
inline fun <T : Any, R> assertNotNull(actual: T?, message: String? = null, block: (T) -> R): R
161
162
/**
163
* Asserts that the value is null
164
* @param actual the value to check
165
* @param message the message to report on failure
166
*/
167
fun assertNull(actual: Any?, message: String? = null)
168
```
169
170
**Usage Examples:**
171
172
```kotlin
173
import kotlin.test.*
174
175
class NullabilityTests {
176
@Test
177
fun nullChecks() {
178
val nullableString: String? = "hello"
179
val nonNullString = assertNotNull(nullableString)
180
assertEquals("hello", nonNullString) // nonNullString is smart-cast to String
181
182
val nullValue: String? = null
183
assertNull(nullValue)
184
}
185
186
@Test
187
fun nullCheckWithBlock() {
188
val user: User? = createUser("test@example.com")
189
assertNotNull(user, "User should be created successfully") { u ->
190
assertEquals("test@example.com", u.email)
191
assertTrue(u.id > 0)
192
}
193
}
194
}
195
```
196
197
### Reference Equality Assertions
198
199
Functions for testing object identity (same reference) vs. structural equality.
200
201
```kotlin { .api }
202
/**
203
* Asserts that expected and actual are the same object reference
204
* @param expected the expected object reference
205
* @param actual the actual object reference
206
* @param message the message to report on failure
207
*/
208
fun <T> assertSame(expected: T, actual: T, message: String? = null)
209
210
/**
211
* Asserts that illegal and actual are not the same object reference
212
* @param illegal the reference that actual should not be
213
* @param actual the actual object reference
214
* @param message the message to report on failure
215
*/
216
fun <T> assertNotSame(illegal: T, actual: T, message: String? = null)
217
```
218
219
**Usage Examples:**
220
221
```kotlin
222
import kotlin.test.*
223
224
class ReferenceTests {
225
@Test
226
fun sameReference() {
227
val obj = MyObject()
228
val sameRef = obj
229
assertSame(obj, sameRef)
230
231
val differentObj = MyObject()
232
assertNotSame(obj, differentObj)
233
}
234
235
@Test
236
fun singletonPattern() {
237
val instance1 = MySingleton.getInstance()
238
val instance2 = MySingleton.getInstance()
239
assertSame(instance1, instance2, "Singleton should return same instance")
240
}
241
}
242
```
243
244
### Collection Assertions
245
246
Specialized assertion functions for validating collection contents and array equality.
247
248
```kotlin { .api }
249
/**
250
* Asserts that the iterable contains the specified element
251
*/
252
fun <T> assertContains(iterable: Iterable<T>, element: T, message: String? = null)
253
254
/**
255
* Asserts that the sequence contains the specified element
256
*/
257
fun <T> assertContains(sequence: Sequence<T>, element: T, message: String? = null)
258
259
/**
260
* Asserts that the array contains the specified element
261
*/
262
fun <T> assertContains(array: Array<T>, element: T, message: String? = null)
263
264
/**
265
* Asserts that primitive arrays contain specified elements
266
*/
267
fun assertContains(array: ByteArray, element: Byte, message: String? = null)
268
fun assertContains(array: ShortArray, element: Short, message: String? = null)
269
fun assertContains(array: IntArray, element: Int, message: String? = null)
270
fun assertContains(array: LongArray, element: Long, message: String? = null)
271
fun assertContains(array: BooleanArray, element: Boolean, message: String? = null)
272
fun assertContains(array: CharArray, element: Char, message: String? = null)
273
274
/**
275
* Asserts that the map contains the specified key
276
*/
277
fun <K, V> assertContains(map: Map<K, V>, key: K, message: String? = null)
278
279
/**
280
* Asserts that the CharSequence contains the specified character or substring
281
*/
282
fun assertContains(charSequence: CharSequence, char: Char, ignoreCase: Boolean = false, message: String? = null)
283
fun assertContains(charSequence: CharSequence, other: CharSequence, ignoreCase: Boolean = false, message: String? = null)
284
fun assertContains(charSequence: CharSequence, regex: Regex, message: String? = null)
285
```
286
287
**Usage Examples:**
288
289
```kotlin
290
import kotlin.test.*
291
292
class CollectionTests {
293
@Test
294
fun listContains() {
295
val numbers = listOf(1, 2, 3, 4, 5)
296
assertContains(numbers, 3)
297
assertContains(numbers, 1)
298
}
299
300
@Test
301
fun arrayContains() {
302
val words = arrayOf("hello", "world", "kotlin")
303
assertContains(words, "kotlin")
304
305
val intArray = intArrayOf(10, 20, 30)
306
assertContains(intArray, 20)
307
}
308
309
@Test
310
fun mapContains() {
311
val userMap = mapOf("admin" to "Alice", "user" to "Bob")
312
assertContains(userMap, "admin")
313
assertContains(userMap, "user")
314
}
315
316
@Test
317
fun stringContains() {
318
val message = "Hello, Kotlin World!"
319
assertContains(message, "Kotlin")
320
assertContains(message, 'K')
321
assertContains(message, "kotlin", ignoreCase = true)
322
assertContains(message, Regex("K\\w+"))
323
}
324
}
325
```
326
327
### Content Equality Assertions
328
329
Functions for deep equality comparison of collections and arrays.
330
331
```kotlin { .api }
332
/**
333
* Asserts that iterables have the same elements in the same order
334
*/
335
fun <T> assertContentEquals(expected: Iterable<T>?, actual: Iterable<T>?, message: String? = null)
336
337
/**
338
* Asserts that sequences have the same elements in the same order
339
*/
340
fun <T> assertContentEquals(expected: Sequence<T>?, actual: Sequence<T>?, message: String? = null)
341
342
/**
343
* Asserts that arrays have the same elements in the same order
344
*/
345
fun <T> assertContentEquals(expected: Array<T>?, actual: Array<T>?, message: String? = null)
346
347
/**
348
* Asserts that primitive arrays have the same elements in the same order
349
*/
350
fun assertContentEquals(expected: ByteArray?, actual: ByteArray?, message: String? = null)
351
fun assertContentEquals(expected: ShortArray?, actual: ShortArray?, message: String? = null)
352
fun assertContentEquals(expected: IntArray?, actual: IntArray?, message: String? = null)
353
fun assertContentEquals(expected: LongArray?, actual: LongArray?, message: String? = null)
354
fun assertContentEquals(expected: FloatArray?, actual: FloatArray?, message: String? = null)
355
fun assertContentEquals(expected: DoubleArray?, actual: DoubleArray?, message: String? = null)
356
fun assertContentEquals(expected: BooleanArray?, actual: BooleanArray?, message: String? = null)
357
fun assertContentEquals(expected: CharArray?, actual: CharArray?, message: String? = null)
358
```
359
360
**Usage Examples:**
361
362
```kotlin
363
import kotlin.test.*
364
365
class ContentEqualityTests {
366
@Test
367
fun listContentEquals() {
368
val expected = listOf(1, 2, 3)
369
val actual = processNumbers(listOf(3, 1, 2)) // sorts the list
370
assertContentEquals(expected, actual)
371
}
372
373
@Test
374
fun arrayContentEquals() {
375
val expected = arrayOf("a", "b", "c")
376
val actual = generateAlphabet(3)
377
assertContentEquals(expected, actual)
378
379
val expectedInts = intArrayOf(1, 2, 3)
380
val actualInts = intArrayOf(1, 2, 3)
381
assertContentEquals(expectedInts, actualInts)
382
}
383
384
@Test
385
fun nullHandling() {
386
assertContentEquals(null, null)
387
388
val emptyList: List<Int>? = emptyList()
389
val nullList: List<Int>? = null
390
assertContentEquals(emptyList, emptyList())
391
}
392
}
393
```
394
395
### Type Assertions
396
397
Functions for runtime type checking with reified generic support.
398
399
```kotlin { .api }
400
/**
401
* Asserts that the value is of the specified type and returns it cast to that type
402
* @param value the value to check and cast
403
* @param message the message to report on failure
404
* @return the value cast to type T
405
*/
406
inline fun <reified T> assertIs(value: Any?, message: String? = null): T
407
408
/**
409
* Asserts that the value is not of the specified type
410
* @param value the value to check
411
* @param message the message to report on failure
412
*/
413
inline fun <reified T> assertIsNot(value: Any?, message: String? = null)
414
```
415
416
**Usage Examples:**
417
418
```kotlin
419
import kotlin.test.*
420
421
class TypeTests {
422
@Test
423
fun typeChecking() {
424
val value: Any = "Hello"
425
val stringValue = assertIs<String>(value)
426
assertEquals("Hello", stringValue) // stringValue is smart-cast to String
427
428
assertIsNot<Int>(value)
429
assertIsNot<List<*>>(value)
430
}
431
432
@Test
433
fun polymorphicTypeChecking() {
434
val shapes: List<Shape> = listOf(Circle(5.0), Rectangle(3.0, 4.0))
435
436
val circle = assertIs<Circle>(shapes[0])
437
assertEquals(5.0, circle.radius)
438
439
val rectangle = assertIs<Rectangle>(shapes[1])
440
assertEquals(3.0, rectangle.width)
441
assertEquals(4.0, rectangle.height)
442
}
443
}
444
```
445
446
### Exception Assertions
447
448
Functions for testing that code throws expected exceptions.
449
450
```kotlin { .api }
451
/**
452
* Asserts that the block throws any exception and returns the exception
453
* @param block the block that should throw an exception
454
* @return the thrown exception
455
*/
456
inline fun assertFails(block: () -> Any?): Throwable
457
458
/**
459
* Asserts that the block throws any exception and returns the exception
460
* @param message the message to report if no exception is thrown
461
* @param block the block that should throw an exception
462
* @return the thrown exception
463
*/
464
inline fun assertFails(message: String?, block: () -> Any?): Throwable
465
466
/**
467
* Asserts that the block throws an exception of the specified type
468
* @param message the message to report on failure
469
* @param block the block that should throw an exception
470
* @return the thrown exception cast to the specified type
471
*/
472
inline fun <reified T : Throwable> assertFailsWith(message: String? = null, block: () -> Any?): T
473
474
/**
475
* Asserts that the block throws an exception of the specified class
476
* @param exceptionClass the expected exception class
477
* @param message the message to report on failure
478
* @param block the block that should throw an exception
479
* @return the thrown exception
480
*/
481
inline fun <T : Throwable> assertFailsWith(exceptionClass: KClass<T>, message: String? = null, block: () -> Any?): T
482
```
483
484
**Usage Examples:**
485
486
```kotlin
487
import kotlin.test.*
488
489
class ExceptionTests {
490
@Test
491
fun anyException() {
492
val exception = assertFails {
493
throw RuntimeException("Something went wrong")
494
}
495
assertTrue(exception.message?.contains("Something went wrong") == true)
496
}
497
498
@Test
499
fun specificExceptionType() {
500
val exception = assertFailsWith<IllegalArgumentException> {
501
validateAge(-1)
502
}
503
assertEquals("Age cannot be negative", exception.message)
504
}
505
506
@Test
507
fun exceptionWithClass() {
508
val exception = assertFailsWith(
509
exceptionClass = NumberFormatException::class,
510
message = "Should throw NumberFormatException for invalid input"
511
) {
512
"not-a-number".toInt()
513
}
514
assertNotNull(exception.message)
515
}
516
517
@Test
518
fun asyncExceptionHandling(): Promise<*> {
519
return Promise.reject(RuntimeException("Async error")).catch { error ->
520
assertFails {
521
throw error.toThrowableOrNull() ?: RuntimeException("Unknown error")
522
}
523
}
524
}
525
}
526
```
527
528
### Utility Functions
529
530
Additional assertion utilities for common testing scenarios.
531
532
```kotlin { .api }
533
/**
534
* Fails the current test unconditionally
535
* @param message the failure message
536
*/
537
fun fail(message: String? = null): Nothing
538
539
/**
540
* Fails the current test with a cause
541
* @param message the failure message
542
* @param cause the underlying cause
543
*/
544
fun fail(message: String? = null, cause: Throwable? = null): Nothing
545
546
/**
547
* Expects that the block returns the expected value
548
* @param expected the expected return value
549
* @param block the block to execute
550
*/
551
inline fun <T> expect(expected: T, block: () -> T)
552
553
/**
554
* Expects that the block returns the expected value with custom message
555
* @param expected the expected return value
556
* @param message the message to report on failure
557
* @param block the block to execute
558
*/
559
inline fun <T> expect(expected: T, message: String?, block: () -> T)
560
561
/**
562
* Marks code as not yet implemented - will always fail
563
* @param block the placeholder block
564
*/
565
fun todo(block: () -> Unit): Nothing
566
```
567
568
**Usage Examples:**
569
570
```kotlin
571
import kotlin.test.*
572
573
class UtilityTests {
574
@Test
575
fun conditionalFailure() {
576
val config = loadConfiguration()
577
if (config.isInvalid()) {
578
fail("Configuration is invalid: ${config.errors}")
579
}
580
}
581
582
@Test
583
fun expectPattern() {
584
expect(42) {
585
calculateAnswer()
586
}
587
588
expect(listOf(1, 2, 3), "List should be sorted") {
589
sortNumbers(listOf(3, 1, 2))
590
}
591
}
592
593
@Test
594
fun todoExample() {
595
// This test will fail until implementation is complete
596
todo {
597
implementNewFeature()
598
}
599
}
600
}