0
# Collection and Array Assertions
1
2
Content equality and membership testing for collections, arrays, ranges, maps, and strings with comprehensive support for all Kotlin types including primitives and unsigned types. These functions provide structural comparison and containment testing essential for validating data structures in tests.
3
4
## Capabilities
5
6
### assertContains - Collections
7
8
Tests whether collections and sequences contain specific elements.
9
10
```kotlin { .api }
11
/**
12
* Asserts that the iterable contains the specified element.
13
* @param iterable The iterable collection to search
14
* @param element The element to find
15
* @param message Optional message to show if assertion fails
16
* @since Kotlin 1.5
17
*/
18
fun <T> assertContains(iterable: Iterable<T>, element: T, message: String? = null)
19
20
/**
21
* Asserts that the sequence contains the specified element.
22
* @param sequence The sequence to search
23
* @param element The element to find
24
* @param message Optional message to show if assertion fails
25
* @since Kotlin 1.5
26
*/
27
fun <T> assertContains(sequence: Sequence<T>, element: T, message: String? = null)
28
```
29
30
**Usage Examples:**
31
32
```kotlin
33
import kotlin.test.assertContains
34
35
@Test
36
fun testCollectionContains() {
37
// List containment
38
val numbers = listOf(1, 2, 3, 4, 5)
39
assertContains(numbers, 3, "List should contain 3")
40
41
// Set containment
42
val colors = setOf("red", "green", "blue")
43
assertContains(colors, "red", "Set should contain red")
44
45
// Sequence containment
46
val sequence = sequenceOf("a", "b", "c")
47
assertContains(sequence, "b", "Sequence should contain 'b'")
48
49
// Custom objects
50
val users = listOf(User("Alice"), User("Bob"), User("Charlie"))
51
assertContains(users, User("Bob"), "Users should contain Bob")
52
}
53
```
54
55
### assertContains - Arrays
56
57
Tests whether arrays contain specific elements, supporting all primitive and reference types.
58
59
```kotlin { .api }
60
/**
61
* Asserts that the array contains the specified element.
62
* @since Kotlin 1.5
63
*/
64
fun <T> assertContains(array: Array<T>, element: T, message: String? = null)
65
66
/**
67
* Array contains functions for primitive types.
68
* @since Kotlin 1.5
69
*/
70
fun assertContains(array: ByteArray, element: Byte, message: String? = null)
71
fun assertContains(array: ShortArray, element: Short, message: String? = null)
72
fun assertContains(array: IntArray, element: Int, message: String? = null)
73
fun assertContains(array: LongArray, element: Long, message: String? = null)
74
fun assertContains(array: BooleanArray, element: Boolean, message: String? = null)
75
fun assertContains(array: CharArray, element: Char, message: String? = null)
76
77
/**
78
* Unsigned array containment (experimental)
79
*/
80
fun assertContains(array: UByteArray, element: UByte, message: String? = null)
81
fun assertContains(array: UShortArray, element: UShort, message: String? = null)
82
fun assertContains(array: UIntArray, element: UInt, message: String? = null)
83
fun assertContains(array: ULongArray, element: ULong, message: String? = null)
84
```
85
86
**Usage Examples:**
87
88
```kotlin
89
import kotlin.test.assertContains
90
91
@Test
92
fun testArrayContains() {
93
// Generic array
94
val stringArray = arrayOf("hello", "world", "kotlin")
95
assertContains(stringArray, "kotlin", "Array should contain 'kotlin'")
96
97
// Primitive arrays
98
val intArray = intArrayOf(10, 20, 30, 40)
99
assertContains(intArray, 30, "Int array should contain 30")
100
101
val charArray = charArrayOf('a', 'b', 'c')
102
assertContains(charArray, 'b', "Char array should contain 'b'")
103
104
val booleanArray = booleanArrayOf(true, false, true)
105
assertContains(booleanArray, false, "Boolean array should contain false")
106
107
// Unsigned arrays (experimental)
108
val uintArray = uintArrayOf(1u, 2u, 3u)
109
assertContains(uintArray, 2u, "UInt array should contain 2u")
110
}
111
```
112
113
### assertContains - Ranges
114
115
Tests whether ranges contain specific values with support for numeric and character ranges.
116
117
```kotlin { .api }
118
/**
119
* Range containment testing
120
*/
121
fun assertContains(range: IntRange, value: Int, message: String? = null)
122
fun assertContains(range: LongRange, value: Long, message: String? = null)
123
fun assertContains(range: CharRange, value: Char, message: String? = null)
124
fun <T : Comparable<T>> assertContains(range: ClosedRange<T>, value: T, message: String? = null)
125
126
/**
127
* Asserts that the range contains the specified value.
128
* @since Kotlin 2.2
129
*/
130
fun <T : Comparable<T>> assertContains(range: OpenEndRange<T>, value: T, message: String? = null)
131
132
/**
133
* Unsigned range containment
134
*/
135
fun assertContains(range: UIntRange, value: UInt, message: String? = null)
136
fun assertContains(range: ULongRange, value: ULong, message: String? = null)
137
```
138
139
**Usage Examples:**
140
141
```kotlin
142
import kotlin.test.assertContains
143
144
@Test
145
fun testRangeContains() {
146
// Numeric ranges
147
val range1to10 = 1..10
148
assertContains(range1to10, 5, "Range 1..10 should contain 5")
149
150
val longRange = 100L..200L
151
assertContains(longRange, 150L, "Long range should contain 150L")
152
153
// Character ranges
154
val letterRange = 'a'..'z'
155
assertContains(letterRange, 'm', "Letter range should contain 'm'")
156
157
// Custom comparable types
158
val dateRange = LocalDate.of(2023, 1, 1)..LocalDate.of(2023, 12, 31)
159
assertContains(dateRange, LocalDate.of(2023, 6, 15), "Date range should contain mid-year date")
160
161
// Unsigned ranges
162
val uintRange = 10u..20u
163
assertContains(uintRange, 15u, "UInt range should contain 15u")
164
}
165
```
166
167
### assertContains - Maps and Strings
168
169
Tests whether maps contain specific keys and strings contain substrings or patterns.
170
171
```kotlin { .api }
172
/**
173
* Map key containment
174
*/
175
fun <K, V> assertContains(map: Map<K, V>, key: K, message: String? = null)
176
177
/**
178
* String/character sequence containment
179
*/
180
fun assertContains(charSequence: CharSequence, char: Char, ignoreCase: Boolean = false, message: String? = null)
181
fun assertContains(charSequence: CharSequence, other: CharSequence, ignoreCase: Boolean = false, message: String? = null)
182
fun assertContains(charSequence: CharSequence, regex: Regex, message: String? = null)
183
```
184
185
**Usage Examples:**
186
187
```kotlin
188
import kotlin.test.assertContains
189
190
@Test
191
fun testMapAndStringContains() {
192
// Map key containment
193
val config = mapOf("host" to "localhost", "port" to 8080, "ssl" to true)
194
assertContains(config, "port", "Config should contain port key")
195
196
// String character containment
197
val text = "Hello, World!"
198
assertContains(text, 'W', false, "Text should contain 'W'")
199
assertContains(text, 'w', true, "Text should contain 'w' (case insensitive)")
200
201
// Substring containment
202
assertContains(text, "World", false, "Text should contain 'World'")
203
assertContains(text, "hello", true, "Text should contain 'hello' (case insensitive)")
204
205
// Regex pattern matching
206
val email = "user@example.com"
207
val emailPattern = Regex("""[\w._%+-]+@[\w.-]+\.[A-Za-z]{2,}""")
208
assertContains(email, emailPattern, "Email should match pattern")
209
210
// Phone number validation
211
val phone = "+1-555-123-4567"
212
val phonePattern = Regex("""\+\d{1,3}-\d{3}-\d{3}-\d{4}""")
213
assertContains(phone, phonePattern, "Phone should match international format")
214
}
215
```
216
217
### assertContentEquals - Collections
218
219
Compares the structural content of collections and sequences for equality.
220
221
```kotlin { .api }
222
/**
223
* Collection content equality testing
224
* @since Kotlin 1.5
225
*/
226
fun <T> assertContentEquals(expected: Iterable<T>?, actual: Iterable<T>?, message: String? = null)
227
228
/**
229
* Sequence content equality testing
230
* @since Kotlin 1.5
231
*/
232
fun <T> assertContentEquals(expected: Sequence<T>?, actual: Sequence<T>?, message: String? = null)
233
234
/**
235
* Set content equality (deprecated - use assertEquals for sets)
236
*/
237
@Deprecated("'assertContentEquals' for Set arguments is ambiguous. Use 'assertEquals' to compare content with the unordered set equality, or cast one of arguments to Iterable to compare the set elements in order of iteration.", level = DeprecationLevel.ERROR, replaceWith = ReplaceWith("assertContentEquals(expected, actual?.asIterable(), message)"))
238
fun <T> assertContentEquals(expected: Set<T>?, actual: Set<T>?, message: String? = null)
239
```
240
241
**Usage Examples:**
242
243
```kotlin
244
import kotlin.test.assertContentEquals
245
246
@Test
247
fun testCollectionContentEquals() {
248
// List content equality (order matters)
249
val expected = listOf(1, 2, 3, 4)
250
val actual = mutableListOf(1, 2, 3, 4)
251
assertContentEquals(expected, actual, "Lists should have same content")
252
253
// Different collection types with same content
254
val originalList = listOf("a", "b", "c")
255
val arrayList = ArrayList(originalList)
256
assertContentEquals(originalList, arrayList, "Different list implementations should be equal")
257
258
// Sequence content equality
259
val sequence1 = sequenceOf(10, 20, 30)
260
val sequence2 = listOf(10, 20, 30).asSequence()
261
assertContentEquals(sequence1, sequence2, "Sequences should have same content")
262
263
// Null handling
264
val nullList: List<String>? = null
265
val anotherNullList: List<String>? = null
266
assertContentEquals(nullList, anotherNullList, "Both null lists should be equal")
267
}
268
```
269
270
### assertContentEquals - Arrays
271
272
Compares the structural content of arrays for equality, supporting all array types.
273
274
```kotlin { .api }
275
/**
276
* Array content equality testing
277
*/
278
fun <T> assertContentEquals(expected: Array<T>?, actual: Array<T>?, message: String? = null)
279
fun assertContentEquals(expected: ByteArray?, actual: ByteArray?, message: String? = null)
280
fun assertContentEquals(expected: ShortArray?, actual: ShortArray?, message: String? = null)
281
fun assertContentEquals(expected: IntArray?, actual: IntArray?, message: String? = null)
282
fun assertContentEquals(expected: LongArray?, actual: LongArray?, message: String? = null)
283
fun assertContentEquals(expected: FloatArray?, actual: FloatArray?, message: String? = null)
284
fun assertContentEquals(expected: DoubleArray?, actual: DoubleArray?, message: String? = null)
285
fun assertContentEquals(expected: BooleanArray?, actual: BooleanArray?, message: String? = null)
286
fun assertContentEquals(expected: CharArray?, actual: CharArray?, message: String? = null)
287
288
/**
289
* Unsigned array content equality (experimental)
290
*/
291
fun assertContentEquals(expected: UByteArray?, actual: UByteArray?, message: String? = null)
292
fun assertContentEquals(expected: UShortArray?, actual: UShortArray?, message: String? = null)
293
fun assertContentEquals(expected: UIntArray?, actual: UIntArray?, message: String? = null)
294
fun assertContentEquals(expected: ULongArray?, actual: ULongArray?, message: String? = null)
295
```
296
297
**Usage Examples:**
298
299
```kotlin
300
import kotlin.test.assertContentEquals
301
302
@Test
303
fun testArrayContentEquals() {
304
// Generic arrays
305
val expected = arrayOf("apple", "banana", "cherry")
306
val actual = arrayOf("apple", "banana", "cherry")
307
assertContentEquals(expected, actual, "String arrays should have same content")
308
309
// Primitive arrays
310
val expectedInts = intArrayOf(1, 2, 3, 4, 5)
311
val aktualInts = intArrayOf(1, 2, 3, 4, 5)
312
assertContentEquals(expectedInts, aktualInts, "Int arrays should have same content")
313
314
val expectedChars = charArrayOf('h', 'e', 'l', 'l', 'o')
315
val actualChars = "hello".toCharArray()
316
assertContentEquals(expectedChars, actualChars, "Char arrays should have same content")
317
318
// Floating point arrays
319
val expectedFloats = floatArrayOf(1.0f, 2.5f, 3.7f)
320
val actualFloats = floatArrayOf(1.0f, 2.5f, 3.7f)
321
assertContentEquals(expectedFloats, actualFloats, "Float arrays should have same content")
322
323
// Unsigned arrays
324
val expectedUInts = uintArrayOf(1u, 2u, 3u)
325
val actualUInts = uintArrayOf(1u, 2u, 3u)
326
assertContentEquals(expectedUInts, actualUInts, "UInt arrays should have same content")
327
328
// Null arrays
329
val nullArray: IntArray? = null
330
val anotherNullArray: IntArray? = null
331
assertContentEquals(nullArray, anotherNullArray, "Both null arrays should be equal")
332
}
333
```
334
335
## Error Handling
336
337
Collection and array assertion functions will throw an `AssertionError` when conditions fail:
338
339
- **assertContains**: Throws when element/key/pattern is not found in the collection/array/range/map/string
340
- **assertContentEquals**: Throws when collections/arrays have different content or structure
341
342
Error messages provide detailed information about the mismatch:
343
344
```kotlin
345
// This will throw: AssertionError: Expected the collection to contain <5>, but it doesn't: <[1, 2, 3, 4]>
346
assertContains(listOf(1, 2, 3, 4), 5)
347
348
// This will throw: AssertionError: Expected <[1, 2, 3]>, actual <[1, 2, 3, 4]>
349
assertContentEquals(listOf(1, 2, 3), listOf(1, 2, 3, 4))
350
```
351
352
## Performance Considerations
353
354
- **Collection containment**: Uses the collection's native `contains()` method for optimal performance
355
- **Array containment**: Performs linear search through array elements
356
- **Content comparison**: Compares elements sequentially, stopping at first difference
357
- **Sequence operations**: May consume the entire sequence during comparison
358
- **Regex matching**: Pattern compilation and matching can be expensive for complex patterns