0
# Collection Assertions
1
2
Rich assertion methods for iterables, lists, sets, and other collections including size, containment, ordering, and exact matching.
3
4
## Capabilities
5
6
### Iterable Subject Creation
7
8
```java { .api }
9
/**
10
* Creates an IterableSubject for asserting about Iterable collections.
11
* @param actual the Iterable under test
12
*/
13
public static IterableSubject assertThat(Iterable<?> actual);
14
```
15
16
### Size and Emptiness Assertions
17
18
Methods for asserting about collection size and emptiness.
19
20
```java { .api }
21
/**
22
* Fails if the collection is not empty.
23
*/
24
public void isEmpty();
25
26
/**
27
* Fails if the collection is empty.
28
*/
29
public void isNotEmpty();
30
31
/**
32
* Fails if the collection does not have the specified size.
33
* @param expectedSize the expected number of elements
34
*/
35
public void hasSize(int expectedSize);
36
```
37
38
**Usage Examples:**
39
40
```java
41
List<String> emptyList = new ArrayList<>();
42
List<String> colors = Arrays.asList("red", "green", "blue");
43
44
assertThat(emptyList).isEmpty();
45
assertThat(colors).isNotEmpty();
46
assertThat(colors).hasSize(3);
47
```
48
49
### Basic Containment Assertions
50
51
Methods for asserting whether collections contain specific elements.
52
53
```java { .api }
54
/**
55
* Fails if the collection does not contain the specified element.
56
* @param element the element that should be present
57
*/
58
public void contains(Object element);
59
60
/**
61
* Fails if the collection contains the specified element.
62
* @param element the element that should not be present
63
*/
64
public void doesNotContain(Object element);
65
66
/**
67
* Fails if the collection contains duplicate elements.
68
*/
69
public void containsNoDuplicates();
70
```
71
72
**Usage Examples:**
73
74
```java
75
List<String> fruits = Arrays.asList("apple", "banana", "cherry");
76
77
assertThat(fruits).contains("apple");
78
assertThat(fruits).doesNotContain("orange");
79
80
List<String> noDuplicates = Arrays.asList("a", "b", "c");
81
assertThat(noDuplicates).containsNoDuplicates();
82
```
83
84
### Equality Assertions
85
86
Collection equality assertion.
87
88
```java { .api }
89
/**
90
* Fails if the collection is not equal to the expected object.
91
* For collections, this performs element-by-element comparison.
92
* @param expected the expected collection
93
*/
94
public void isEqualTo(Object expected);
95
```
96
97
### Multiple Element Containment
98
99
Methods for asserting about multiple elements with "any" and "none" semantics.
100
101
```java { .api }
102
/**
103
* Fails if the collection does not contain at least one of the specified elements.
104
* @param first the first element to check
105
* @param rest additional elements to check
106
*/
107
public void containsAnyOf(Object first, Object... rest);
108
109
/**
110
* Fails if the collection does not contain at least one element from the given iterable.
111
* @param expected the iterable containing elements to check
112
*/
113
public void containsAnyIn(Iterable<?> expected);
114
115
/**
116
* Fails if the collection does not contain at least one element from the given array.
117
* @param expected the array containing elements to check
118
*/
119
public void containsAnyIn(Object[] expected);
120
121
/**
122
* Fails if the collection contains any of the specified elements.
123
* @param first the first element to check
124
* @param rest additional elements to check
125
*/
126
public void containsNoneOf(Object first, Object... rest);
127
128
/**
129
* Fails if the collection contains any element from the given iterable.
130
* @param excluded the iterable containing elements that should not be present
131
*/
132
public void containsNoneIn(Iterable<?> excluded);
133
134
/**
135
* Fails if the collection contains any element from the given array.
136
* @param excluded the array containing elements that should not be present
137
*/
138
public void containsNoneIn(Object[] excluded);
139
```
140
141
**Usage Examples:**
142
143
```java
144
List<String> colors = Arrays.asList("red", "green", "blue");
145
List<String> primaryColors = Arrays.asList("red", "blue", "yellow");
146
List<String> badColors = Arrays.asList("brown", "gray");
147
148
// At least one match
149
assertThat(colors).containsAnyOf("red", "purple", "orange");
150
assertThat(colors).containsAnyIn(primaryColors);
151
assertThat(colors).containsAnyIn(new String[]{"red", "yellow"});
152
153
// No matches
154
assertThat(colors).containsNoneOf("purple", "orange", "pink");
155
assertThat(colors).containsNoneIn(badColors);
156
assertThat(colors).containsNoneIn(new String[]{"brown", "gray"});
157
```
158
159
### Exact Match Assertions
160
161
Methods for asserting exact collection contents with optional ordering.
162
163
```java { .api }
164
/**
165
* Fails if the collection is not empty.
166
*/
167
public Ordered containsExactly();
168
169
/**
170
* Fails if the collection does not contain exactly the specified elements.
171
* @param first the first expected element
172
* @param rest additional expected elements
173
*/
174
public Ordered containsExactly(Object first, Object... rest);
175
176
/**
177
* Fails if the collection does not contain exactly the elements in the given iterable.
178
* @param expected the iterable containing the expected elements
179
*/
180
public Ordered containsExactlyElementsIn(Iterable<?> expected);
181
182
/**
183
* Fails if the collection does not contain exactly the elements in the given array.
184
* @param expected the array containing the expected elements
185
*/
186
public Ordered containsExactlyElementsIn(Object[] expected);
187
```
188
189
**Usage Examples:**
190
191
```java
192
List<String> empty = new ArrayList<>();
193
List<String> colors = Arrays.asList("red", "green", "blue");
194
List<String> moreColors = Arrays.asList("red", "green", "blue", "yellow");
195
196
// Exact empty match
197
assertThat(empty).containsExactly();
198
199
// Exact element match (order doesn't matter by default)
200
assertThat(colors).containsExactly("blue", "red", "green");
201
assertThat(colors).containsExactlyElementsIn(Arrays.asList("green", "blue", "red"));
202
assertThat(colors).containsExactlyElementsIn(new String[]{"blue", "green", "red"});
203
204
// With ordering constraint
205
assertThat(colors).containsExactly("red", "green", "blue").inOrder();
206
assertThat(colors).containsExactlyElementsIn(Arrays.asList("red", "green", "blue")).inOrder();
207
```
208
209
### At Least Assertions
210
211
Methods for asserting that collections contain at least the specified elements.
212
213
```java { .api }
214
/**
215
* Fails if the collection does not contain at least the specified elements.
216
* @param first the first required element
217
* @param rest additional required elements
218
*/
219
public void containsAtLeast(Object first, Object... rest);
220
221
/**
222
* Fails if the collection does not contain at least the elements in the given iterable.
223
* @param expected the iterable containing the required elements
224
*/
225
public void containsAtLeastElementsIn(Iterable<?> expected);
226
227
/**
228
* Fails if the collection does not contain at least the elements in the given array.
229
* @param expected the array containing the required elements
230
*/
231
public void containsAtLeastElementsIn(Object[] expected);
232
```
233
234
**Usage Examples:**
235
236
```java
237
List<String> colors = Arrays.asList("red", "green", "blue", "yellow", "purple");
238
239
// Must contain at least these elements (can have more)
240
assertThat(colors).containsAtLeast("red", "blue");
241
assertThat(colors).containsAtLeastElementsIn(Arrays.asList("green", "yellow"));
242
assertThat(colors).containsAtLeastElementsIn(new String[]{"red", "purple"});
243
```
244
245
### Ordering Assertions
246
247
Methods for asserting about element ordering within collections.
248
249
```java { .api }
250
/**
251
* Fails if the elements are not in natural order (according to Comparable).
252
*/
253
public void isInOrder();
254
255
/**
256
* Fails if the elements are not in order according to the given comparator.
257
* @param comparator the comparator to use for ordering
258
*/
259
public void isInOrder(Comparator<?> comparator);
260
261
/**
262
* Fails if the elements are not in strict natural order (no equal adjacent elements).
263
*/
264
public void isInStrictOrder();
265
266
/**
267
* Fails if the elements are not in strict order according to the given comparator.
268
* @param comparator the comparator to use for ordering
269
*/
270
public void isInStrictOrder(Comparator<?> comparator);
271
```
272
273
**Usage Examples:**
274
275
```java
276
import java.util.Comparator;
277
278
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
279
List<Integer> strictNumbers = Arrays.asList(1, 3, 5, 7, 9);
280
List<String> words = Arrays.asList("apple", "banana", "cherry");
281
282
// Natural ordering
283
assertThat(numbers).isInOrder();
284
assertThat(strictNumbers).isInStrictOrder();
285
assertThat(words).isInOrder();
286
287
// Custom comparator ordering
288
List<String> byLength = Arrays.asList("cat", "dog", "elephant");
289
assertThat(byLength).isInOrder(Comparator.comparing(String::length));
290
291
// Reverse ordering
292
List<String> reversed = Arrays.asList("zebra", "monkey", "cat");
293
assertThat(reversed).isInOrder(Comparator.reverseOrder());
294
```
295
296
### Custom Element Comparison
297
298
Methods for custom element comparison using Correspondence.
299
300
```java { .api }
301
/**
302
* Starts a method chain for a check in which the actual elements are compared to expected
303
* elements using the given Correspondence.
304
* @param correspondence the correspondence to use for element comparison
305
*/
306
public <A, E> UsingCorrespondence<A, E> comparingElementsUsing(Correspondence<? super A, ? super E> correspondence);
307
308
/**
309
* Starts a method chain for a check in which the actual elements are compared to expected
310
* elements using the given correspondence and displays diffs using the provided formatter.
311
* @param formatter the formatter to use for displaying diffs between elements
312
*/
313
public <T> UsingCorrespondence<T, T> formattingDiffsUsing(DiffFormatter<? super T, ? super T> formatter);
314
```
315
316
**Usage Examples:**
317
318
```java
319
import com.google.common.truth.Correspondence;
320
321
// Compare strings ignoring case
322
Correspondence<String, String> CASE_INSENSITIVE =
323
Correspondence.from((actual, expected) -> actual.equalsIgnoreCase(expected), "ignoring case");
324
325
List<String> actualNames = Arrays.asList("Alice", "BOB", "charlie");
326
List<String> expectedNames = Arrays.asList("alice", "bob", "Charlie");
327
328
assertThat(actualNames)
329
.comparingElementsUsing(CASE_INSENSITIVE)
330
.containsExactlyElementsIn(expectedNames);
331
332
// Compare objects by specific field
333
Correspondence<Person, String> BY_NAME =
334
Correspondence.transforming(Person::getName, "by name");
335
336
List<Person> people = Arrays.asList(new Person("Alice"), new Person("Bob"));
337
assertThat(people)
338
.comparingElementsUsing(BY_NAME)
339
.containsExactly("Alice", "Bob");
340
```
341
342
### Advanced Collection Testing Examples
343
344
Common patterns for collection testing:
345
346
```java
347
// Testing filtered results
348
List<User> users = getAllUsers();
349
List<User> activeUsers = users.stream()
350
.filter(User::isActive)
351
.collect(toList());
352
353
assertThat(activeUsers).isNotEmpty();
354
assertThat(activeUsers).hasSize(expectedActiveCount);
355
assertThat(activeUsers).containsAtLeast(knownActiveUser1, knownActiveUser2);
356
357
// Testing transformation results
358
List<String> names = users.stream()
359
.map(User::getName)
360
.collect(toList());
361
362
assertThat(names).containsNoDuplicates();
363
assertThat(names).containsAtLeastElementsIn(expectedNames);
364
assertThat(names).isInOrder(String.CASE_INSENSITIVE_ORDER);
365
366
// Testing set operations
367
Set<String> set1 = Set.of("a", "b", "c");
368
Set<String> set2 = Set.of("b", "c", "d");
369
Set<String> intersection = Sets.intersection(set1, set2);
370
371
assertThat(intersection).containsExactly("b", "c");
372
assertThat(intersection).hasSize(2);
373
```
374
375
## Types
376
377
```java { .api }
378
/**
379
* Subject class for making assertions about Iterable collections.
380
*/
381
public class IterableSubject extends Subject {
382
/**
383
* Constructor for IterableSubject.
384
* @param metadata failure metadata for context
385
* @param actual the Iterable under test
386
*/
387
protected IterableSubject(FailureMetadata metadata, Iterable<?> actual);
388
}
389
390
/**
391
* Interface returned by containsExactly methods to enforce ordering constraints.
392
*/
393
public interface Ordered {
394
/**
395
* Enforces that the elements appear in the specified order.
396
*/
397
void inOrder();
398
}
399
400
/**
401
* Result of comparingElementsUsing() providing custom element comparison methods.
402
*/
403
public class UsingCorrespondence<A, E> {
404
/**
405
* Fails if the iterable does not contain exactly the specified elements using the correspondence.
406
* @param expected the expected elements
407
*/
408
public Ordered containsExactly(E... expected);
409
410
/**
411
* Fails if the iterable does not contain exactly the elements in the given iterable using the correspondence.
412
* @param expected the iterable containing expected elements
413
*/
414
public Ordered containsExactlyElementsIn(Iterable<? extends E> expected);
415
416
/**
417
* Fails if the iterable does not contain at least the specified elements using the correspondence.
418
* @param expected the required elements
419
*/
420
public void containsAtLeast(E... expected);
421
422
/**
423
* Fails if the iterable does not contain at least the elements in the given iterable using the correspondence.
424
* @param expected the iterable containing required elements
425
*/
426
public void containsAtLeastElementsIn(Iterable<? extends E> expected);
427
428
/**
429
* Fails if the iterable does not contain any of the specified elements using the correspondence.
430
* @param expected the elements to check for
431
*/
432
public void containsAnyOf(E... expected);
433
434
/**
435
* Fails if the iterable contains any of the specified elements using the correspondence.
436
* @param excluded the elements that should not be present
437
*/
438
public void containsNoneOf(E... excluded);
439
440
/**
441
* Fails if the iterable does not contain the expected element using the correspondence.
442
* @param expected the element that should be present
443
*/
444
public void contains(E expected);
445
446
/**
447
* Fails if the iterable contains the excluded element using the correspondence.
448
* @param excluded the element that should not be present
449
*/
450
public void doesNotContain(E excluded);
451
452
/**
453
* Specifies functions to derive keys from actual and expected elements for diff display.
454
* @param actualKeyFunction function to derive keys from actual elements
455
* @param expectedKeyFunction function to derive keys from expected elements
456
*/
457
public UsingCorrespondence<A, E> displayingDiffsPairedBy(
458
Function<? super A, ?> actualKeyFunction, Function<? super E, ?> expectedKeyFunction);
459
460
/**
461
* Specifies a function to derive keys from expected elements for diff display.
462
* @param keyFunction function to derive keys from expected elements
463
*/
464
public UsingCorrespondence<A, E> displayingDiffsPairedBy(Function<? super E, ?> keyFunction);
465
}
466
```