-
-
Notifications
You must be signed in to change notification settings - Fork 683
/
SoftAssertionsTest.java
2690 lines (2535 loc) · 119 KB
/
SoftAssertionsTest.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* Copyright 2012-2022 the original author or authors.
*/
package org.assertj.core.api;
import static java.lang.String.format;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Collections.emptyList;
import static java.util.stream.Collectors.toList;
import static org.assertj.core.api.Assertions.as;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.entry;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.in;
import static org.assertj.core.api.Assertions.not;
import static org.assertj.core.api.Assertions.tuple;
import static org.assertj.core.api.BDDAssertions.then;
import static org.assertj.core.api.InstanceOfAssertFactories.STRING;
import static org.assertj.core.api.InstanceOfAssertFactories.THROWABLE;
import static org.assertj.core.api.InstanceOfAssertFactories.type;
import static org.assertj.core.api.SoftAssertions.assertSoftly;
import static org.assertj.core.data.TolkienCharacter.Race.ELF;
import static org.assertj.core.data.TolkienCharacter.Race.HOBBIT;
import static org.assertj.core.data.TolkienCharacter.Race.MAN;
import static org.assertj.core.presentation.UnicodeRepresentation.UNICODE_REPRESENTATION;
import static org.assertj.core.test.AlwaysEqualComparator.alwaysEqual;
import static org.assertj.core.test.ErrorMessagesForTest.shouldBeEqualMessage;
import static org.assertj.core.test.Maps.mapOf;
import static org.assertj.core.test.Name.lastNameComparator;
import static org.assertj.core.test.Name.name;
import static org.assertj.core.util.Arrays.array;
import static org.assertj.core.util.DateUtil.parseDatetime;
import static org.assertj.core.util.Lists.list;
import static org.assertj.core.util.Sets.newLinkedHashSet;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.MalformedURLException;
import java.net.URI;
import java.nio.file.Path;
import java.time.Duration;
import java.time.LocalTime;
import java.time.OffsetTime;
import java.time.Period;
import java.time.ZoneOffset;
import java.util.Collection;
import java.util.Deque;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.OptionalDouble;
import java.util.OptionalInt;
import java.util.OptionalLong;
import java.util.Spliterator;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicIntegerArray;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicLongArray;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicReferenceArray;
import java.util.function.Consumer;
import java.util.function.DoublePredicate;
import java.util.function.Function;
import java.util.function.IntPredicate;
import java.util.function.LongPredicate;
import java.util.function.Predicate;
import java.util.stream.DoubleStream;
import java.util.stream.IntStream;
import java.util.stream.LongStream;
import java.util.stream.Stream;
import org.assertj.core.api.ClassAssertBaseTest.AnnotatedClass;
import org.assertj.core.api.ClassAssertBaseTest.AnotherAnnotation;
import org.assertj.core.api.ClassAssertBaseTest.MyAnnotation;
import org.assertj.core.api.iterable.ThrowingExtractor;
import org.assertj.core.api.test.ComparableExample;
import org.assertj.core.data.MapEntry;
import org.assertj.core.data.TolkienCharacter;
import org.assertj.core.data.TolkienCharacterAssert;
import org.assertj.core.test.Animal;
import org.assertj.core.test.CartoonCharacter;
import org.assertj.core.test.CaseInsensitiveStringComparator;
import org.assertj.core.test.Name;
import org.assertj.core.test.Person;
import org.assertj.core.util.Lists;
import org.assertj.core.util.VisibleForTesting;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.opentest4j.MultipleFailuresError;
/**
* Tests for <code>{@link SoftAssertions}</code>.
*
* @author Brian Laframboise
*/
@DisplayName("Soft assertions")
class SoftAssertionsTest extends BaseAssertionsTest {
private SoftAssertions softly;
private CartoonCharacter homer;
private CartoonCharacter fred;
private CartoonCharacter lisa;
private CartoonCharacter maggie;
private CartoonCharacter bart;
private Map<String, Object> iterableMap;
private static final ThrowingExtractor<Name, String, Exception> throwingFirstNameFunction = Name::getFirst;
private static final ThrowingExtractor<Name, String, Exception> throwingLastNameFunction = Name::getLast;
private static final Function<Name, String> firstNameFunction = Name::getFirst;
private static final Function<Name, String> lastNameFunction = Name::getLast;
private static final Function<? super CartoonCharacter, ? extends Collection<CartoonCharacter>> childrenExtractor = CartoonCharacter::getChildren;
@BeforeEach
void setup() {
Assertions.setRemoveAssertJRelatedElementsFromStackTrace(false);
softly = new SoftAssertions();
bart = new CartoonCharacter("Bart Simpson");
lisa = new CartoonCharacter("Lisa Simpson");
maggie = new CartoonCharacter("Maggie Simpson");
homer = new CartoonCharacter("Homer Simpson");
homer.getChildren().add(bart);
homer.getChildren().add(lisa);
homer.getChildren().add(maggie);
CartoonCharacter pebbles = new CartoonCharacter("Pebbles Flintstone");
fred = new CartoonCharacter("Fred Flintstone");
fred.getChildren().add(pebbles);
List<String> names = list("Dave", "Jeff");
LinkedHashSet<String> jobs = newLinkedHashSet("Plumber", "Builder");
Iterable<String> cities = list("Dover", "Boston", "Paris");
int[] ranks = { 1, 2, 3 };
iterableMap = new LinkedHashMap<>();
iterableMap.put("name", names);
iterableMap.put("job", jobs);
iterableMap.put("city", cities);
iterableMap.put("rank", ranks);
}
@Test
void all_assertions_should_pass() {
softly.assertThat(1).isEqualTo(1);
softly.assertThat(Lists.newArrayList(1, 2)).containsOnly(1, 2);
softly.assertAll();
}
@Test
void should_be_able_to_catch_exceptions_thrown_by_map_assertions() {
// GIVEN
Map<String, String> map = mapOf(MapEntry.entry("54", "55"));
// WHEN
softly.assertThat(map).contains(MapEntry.entry("1", "2")).isEmpty();
// THEN
List<Throwable> errors = softly.errorsCollected();
assertThat(errors).hasSize(2);
assertThat(errors.get(0)).hasMessageStartingWith(format("%nExpecting map:%n"
+ " {\"54\"=\"55\"}%n"
+ "to contain entries:%n"
+ " [\"1\"=\"2\"]%n"
+ "but could not find the following map entries:%n"
+ " [\"1\"=\"2\"]"));
assertThat(errors.get(1)).hasMessageStartingWith(format("%nExpecting empty but was: {\"54\"=\"55\"}"));
}
@SuppressWarnings({ "deprecation" })
@Test
void should_be_able_to_catch_exceptions_thrown_by_all_proxied_methods() throws MalformedURLException {
try {
softly.assertThat(BigDecimal.ZERO).isEqualTo(BigDecimal.ONE);
softly.assertThat(Boolean.FALSE).isTrue();
softly.assertThat(false).isTrue();
softly.assertThat(new boolean[] { false }).isEqualTo(new boolean[] { true });
softly.assertThat(Byte.valueOf((byte) 0)).isEqualTo((byte) 1);
softly.assertThat((byte) 2).inHexadecimal().isEqualTo((byte) 3);
softly.assertThat(new byte[] { 4 }).isEqualTo(new byte[] { 5 });
softly.assertThat(Character.valueOf((char) 65)).isEqualTo(Character.valueOf((char) 66));
softly.assertThat((char) 67).isEqualTo((char) 68);
softly.assertThat(new char[] { 69 }).isEqualTo(new char[] { 70 });
softly.assertThat(new StringBuilder("a")).isEqualTo(new StringBuilder("b"));
softly.assertThat(Object.class).isEqualTo(String.class);
softly.assertThat(parseDatetime("1999-12-31T23:59:59")).isEqualTo(parseDatetime("2000-01-01T00:00:01"));
softly.assertThat(Double.valueOf(6.0d)).isEqualTo(Double.valueOf(7.0d));
softly.assertThat(8.0d).isEqualTo(9.0d);
softly.assertThat(new double[] { 10.0d }).isEqualTo(new double[] { 11.0d });
softly.assertThat(new File("a"))
.overridingErrorMessage(shouldBeEqualMessage("File(a)", "File(b)"))
.isEqualTo(new File("b"));
softly.assertThat(Float.valueOf(12f)).isEqualTo(Float.valueOf(13f));
softly.assertThat(14f).isEqualTo(15f);
softly.assertThat(new float[] { 16f }).isEqualTo(new float[] { 17f });
softly.assertThat(new ByteArrayInputStream(new byte[] { (byte) 65 }))
.hasSameContentAs(new ByteArrayInputStream(new byte[] { (byte) 66 }));
softly.assertThat(Integer.valueOf(20)).isEqualTo(Integer.valueOf(21));
softly.assertThat(22).isEqualTo(23);
softly.assertThat(new int[] { 24 }).isEqualTo(new int[] { 25 });
softly.assertThat((Iterable<String>) Lists.newArrayList("26")).isEqualTo(Lists.newArrayList("27"));
softly.assertThat(list("28").iterator()).isExhausted();
softly.assertThat(list("30")).isEqualTo(Lists.newArrayList("31"));
softly.assertThat(Long.valueOf(32L)).isEqualTo(Long.valueOf(33L));
softly.assertThat(34L).isEqualTo(35L);
softly.assertThat(new long[] { 36L }).isEqualTo(new long[] { 37L });
softly.assertThat(mapOf(MapEntry.entry("38", "39"))).isEqualTo(mapOf(MapEntry.entry("40", "41")));
softly.assertThat(Short.valueOf((short) 42)).isEqualTo(Short.valueOf((short) 43));
softly.assertThat((short) 44).isEqualTo((short) 45);
softly.assertThat(new short[] { (short) 46 }).isEqualTo(new short[] { (short) 47 });
softly.assertThat("48").isEqualTo("49");
softly.assertThat(new Object() {
@Override
public String toString() {
return "50";
}
}).isEqualTo(new Object() {
@Override
public String toString() {
return "51";
}
});
softly.assertThat(new Object[] { new Object() {
@Override
public String toString() {
return "52";
}
} }).isEqualTo(new Object[] { new Object() {
@Override
public String toString() {
return "53";
}
} });
final IllegalArgumentException illegalArgumentException = new IllegalArgumentException("IllegalArgumentException message");
softly.assertThat(illegalArgumentException).hasMessage("NullPointerException message");
softly.assertThatThrownBy(() -> {
throw new Exception("something was wrong");
}).hasMessage("something was good");
softly.assertThat(mapOf(MapEntry.entry("54", "55"))).contains(MapEntry.entry("1", "2"));
softly.assertThat(LocalTime.of(12, 0)).isEqualTo(LocalTime.of(13, 0));
softly.assertThat(OffsetTime.of(12, 0, 0, 0, ZoneOffset.UTC))
.isEqualTo(OffsetTime.of(13, 0, 0, 0, ZoneOffset.UTC));
softly.assertThat(Optional.of("not empty")).isEqualTo("empty");
softly.assertThat(OptionalInt.of(0)).isEqualTo(1);
softly.assertThat(OptionalDouble.of(0.0)).isEqualTo(1.0);
softly.assertThat(OptionalLong.of(0L)).isEqualTo(1L);
softly.assertThat(URI.create("http://assertj.org")).hasPort(8888);
softly.assertThat(CompletableFuture.completedFuture("done")).hasFailed();
softly.assertThat((Predicate<String>) s -> s.equals("something")).accepts("something else");
softly.assertThat((IntPredicate) s -> s == 1).accepts(2);
softly.assertThat((LongPredicate) s -> s == 1).accepts(2);
softly.assertThat((DoublePredicate) s -> s == 1).accepts(2);
softly.assertThat(URI.create("http://assertj.org:80").toURL()).hasNoPort();
softly.assertThat(Duration.ofHours(10)).hasHours(5);
softly.assertThat(Period.ofDays(1)).hasDays(2);
softly.assertAll();
fail("Should not reach here");
} catch (MultipleFailuresError e) {
List<String> errors = e.getFailures().stream().map(Object::toString).collect(toList());
assertThat(errors).hasSize(55);
assertThat(errors.get(0)).contains(shouldBeEqualMessage("0", "1"));
assertThat(errors.get(1)).contains(format("%nExpecting value to be true but was false"));
assertThat(errors.get(2)).contains(format("%nExpecting value to be true but was false"));
assertThat(errors.get(3)).contains(shouldBeEqualMessage("[false]", "[true]"));
assertThat(errors.get(4)).contains(shouldBeEqualMessage("0", "1"));
assertThat(errors.get(5)).contains(shouldBeEqualMessage("0x02", "0x03"));
assertThat(errors.get(6)).contains(shouldBeEqualMessage("[4]", "[5]"));
assertThat(errors.get(7)).contains(shouldBeEqualMessage("'A'", "'B'"));
assertThat(errors.get(8)).contains(shouldBeEqualMessage("'C'", "'D'"));
assertThat(errors.get(9)).contains(shouldBeEqualMessage("['E']", "['F']"));
assertThat(errors.get(10)).contains(shouldBeEqualMessage("a", "b"));
assertThat(errors.get(11)).contains(shouldBeEqualMessage("java.lang.Object", "java.lang.String"));
assertThat(errors.get(12)).contains(shouldBeEqualMessage("1999-12-31T23:59:59.000 (java.util.Date)",
"2000-01-01T00:00:01.000 (java.util.Date)"));
assertThat(errors.get(13)).contains(shouldBeEqualMessage("6.0", "7.0"));
assertThat(errors.get(14)).contains(shouldBeEqualMessage("8.0", "9.0"));
assertThat(errors.get(15)).contains(shouldBeEqualMessage("[10.0]", "[11.0]"));
assertThat(errors.get(16)).contains(shouldBeEqualMessage("File(a)", "File(b)"));
assertThat(errors.get(17)).contains(shouldBeEqualMessage("12.0f", "13.0f"));
assertThat(errors.get(18)).contains(shouldBeEqualMessage("14.0f", "15.0f"));
assertThat(errors.get(19)).contains(shouldBeEqualMessage("[16.0f]", "[17.0f]"));
assertThat(errors.get(20)).contains(format("%nInputStreams do not have same content:%n%n"
+ "Changed content at line 1:%n"
+ "expecting:%n"
+ " [\"B\"]%n"
+ "but was:%n"
+ " [\"A\"]%n"));
assertThat(errors.get(21)).contains(shouldBeEqualMessage("20", "21"));
assertThat(errors.get(22)).contains(shouldBeEqualMessage("22", "23"));
assertThat(errors.get(23)).contains(shouldBeEqualMessage("[24]", "[25]"));
assertThat(errors.get(24)).contains(shouldBeEqualMessage("[\"26\"]", "[\"27\"]"));
assertThat(errors.get(25)).contains(format("Expecting the iterator under test to be exhausted"));
assertThat(errors.get(26)).contains(shouldBeEqualMessage("[\"30\"]", "[\"31\"]"));
assertThat(errors.get(27)).contains(shouldBeEqualMessage("32L", "33L"));
assertThat(errors.get(28)).contains(shouldBeEqualMessage("34L", "35L"));
assertThat(errors.get(29)).contains(shouldBeEqualMessage("[36L]", "[37L]"));
assertThat(errors.get(30)).contains(shouldBeEqualMessage("{\"38\"=\"39\"}", "{\"40\"=\"41\"}"));
assertThat(errors.get(31)).contains(shouldBeEqualMessage("42", "43"));
assertThat(errors.get(31)).contains(shouldBeEqualMessage("42", "43"));
assertThat(errors.get(32)).contains(shouldBeEqualMessage("44", "45"));
assertThat(errors.get(33)).contains(shouldBeEqualMessage("[46]", "[47]"));
assertThat(errors.get(34)).contains(shouldBeEqualMessage("\"48\"", "\"49\""));
assertThat(errors.get(35)).contains(shouldBeEqualMessage("50", "51"));
assertThat(errors.get(36)).contains(shouldBeEqualMessage("[52]", "[53]"));
assertThat(errors.get(37)).contains(format("%nExpecting message to be:%n"
+ " \"NullPointerException message\"%n"
+ "but was:%n"
+ " \"IllegalArgumentException message\""));
assertThat(errors.get(38)).contains(format("%nExpecting message to be:%n"
+ " \"something was good\"%n"
+ "but was:%n"
+ " \"something was wrong\""));
assertThat(errors.get(39)).contains(format("%nExpecting map:%n"
+ " {\"54\"=\"55\"}%n"
+ "to contain entries:%n"
+ " [\"1\"=\"2\"]%n"
+ "but could not find the following map entries:%n"
+ " [\"1\"=\"2\"]"));
assertThat(errors.get(40)).contains(shouldBeEqualMessage("12:00", "13:00"));
assertThat(errors.get(41)).contains(shouldBeEqualMessage("12:00Z", "13:00Z"));
assertThat(errors.get(42)).contains(shouldBeEqualMessage("Optional[not empty]", "\"empty\""));
assertThat(errors.get(43)).contains(shouldBeEqualMessage("OptionalInt[0]", "1"));
assertThat(errors.get(44)).contains(shouldBeEqualMessage("OptionalDouble[0.0]", "1.0"));
assertThat(errors.get(45)).contains(shouldBeEqualMessage("OptionalLong[0]", "1L"));
assertThat(errors.get(46)).contains("Expecting port of");
assertThat(errors.get(47)).contains("to have failed");
assertThat(errors.get(48)).contains(format("%nExpecting actual:%n given predicate%n"
+ "to accept \"something else\" but it did not."));
assertThat(errors.get(49)).contains(format("%nExpecting actual:%n given predicate%n"
+ "to accept 2 but it did not."));
assertThat(errors.get(50)).contains(format("%nExpecting actual:%n given predicate%n"
+ "to accept 2L but it did not."));
assertThat(errors.get(51)).contains(format("%nExpecting actual:%n given predicate%n"
+ "to accept 2.0 but it did not."));
assertThat(errors.get(52)).contains(format("%nExpecting actual:%n"
+ " <http://assertj.org:80>%n"
+ "not to have a port but had:%n"
+ " <80>"));
assertThat(errors.get(53)).contains(format("%nExpecting Duration:%n"
+ " 10H%n"
+ "to have 5L hours but had 10L"));
assertThat(errors.get(54)).contains(format("%nExpecting Period:%n P1D%nto have 2 days but had 1"));
}
}
@Test
void should_pass_when_using_extracting_with_object() {
// GIVEN
Name name = name("John", "Doe");
// WHEN
softly.assertThat(name)
.extracting("first", "last")
.contains("John", "Doe");
softly.assertThat(name)
.extracting("first")
.isEqualTo("John");
softly.assertThat(name)
.extracting("first", as(STRING))
.startsWith("Jo");
softly.assertThat(name)
.extracting(Name::getFirst, Name::getLast)
.contains("John", "Doe");
softly.assertThat(name)
.extracting(Name::getFirst)
.isEqualTo("John");
softly.assertThat(name)
.extracting(Name::getFirst, as(STRING))
.startsWith("Jo");
// THEN
assertThat(softly.errorsCollected()).isEmpty();
}
@Test
void should_pass_when_using_extracting_with_list() {
// GIVEN
List<Name> names = list(Name.name("John", "Doe"), name("Jane", "Doe"));
// WHEN
softly.assertThat(names)
.overridingErrorMessage("overridingErrorMessage with extracting(String)")
.extracting("first")
.contains("John")
.contains("Jane")
.contains("Foo1");
softly.assertThat(names)
.as("using extracting(Extractor)")
.extracting(Name::getFirst)
.contains("John")
.contains("Jane")
.contains("Foo2");
softly.assertThat(names)
.as("using extracting(..., Class)")
.extracting("first", String.class)
.contains("John")
.contains("Jane")
.contains("Foo3");
softly.assertThat(names)
.as("using extracting(...)")
.extracting("first", "last")
.contains(tuple("John", "Doe"))
.contains(tuple("Jane", "Doe"))
.contains(tuple("Foo", "4"));
softly.assertThat(names)
.as("using extractingResultOf(method, Class)")
.extractingResultOf("getFirst", String.class)
.contains("John")
.contains("Jane")
.contains("Foo5");
softly.assertThat(names)
.as("using extractingResultOf(method)")
.extractingResultOf("getFirst")
.contains("John")
.contains("Jane")
.contains("Foo6");
// THEN
List<Throwable> errorsCollected = softly.errorsCollected();
assertThat(errorsCollected).hasSize(6);
assertThat(errorsCollected.get(0)).hasMessage("overridingErrorMessage with extracting(String)");
assertThat(errorsCollected.get(1)).hasMessageContaining("Foo2");
assertThat(errorsCollected.get(2)).hasMessageContaining("Foo3");
assertThat(errorsCollected.get(3)).hasMessageContaining("Foo")
.hasMessageContaining("4");
assertThat(errorsCollected.get(4)).hasMessageContaining("Foo5");
assertThat(errorsCollected.get(5)).hasMessageContaining("Foo6");
}
@Test
void should_pass_when_using_extracting_with_iterable() {
Iterable<Name> names = list(name("John", "Doe"), name("Jane", "Doe"));
try (AutoCloseableSoftAssertions softly = new AutoCloseableSoftAssertions()) {
softly.assertThat(names)
.as("using extracting()")
.extracting("first")
.contains("John")
.contains("Jane");
softly.assertThat(names)
.as("using extracting(Extractor)")
.extracting(Name::getFirst)
.contains("John")
.contains("Jane");
softly.assertThat(names)
.as("using extracting(..., Class)")
.extracting("first", String.class)
.contains("John")
.contains("Jane");
softly.assertThat(names)
.as("using extracting(...)")
.extracting("first", "last")
.contains(tuple("John", "Doe"))
.contains(tuple("Jane", "Doe"));
softly.assertThat(names)
.as("using extractingResultOf(method, Class)")
.extractingResultOf("getFirst", String.class)
.contains("John")
.contains("Jane");
softly.assertThat(names)
.as("using extractingResultOf(method)")
.extractingResultOf("getFirst")
.contains("John")
.contains("Jane");
}
}
@Test
void should_pass_when_using_extracting_with_map() {
// GIVEN
Map<String, Object> map = mapOf(entry("name", "kawhi"), entry("age", 25));
// WHEN
softly.assertThat(map)
.extractingByKeys("name", "age")
.contains("kawhi", 25);
softly.assertThat(map)
.extractingByKey("name")
.isEqualTo("kawhi");
softly.assertThat(map)
.extractingByKey("name", as(STRING))
.startsWith("kaw");
softly.assertThat(map)
.extractingFromEntries(Map.Entry::getKey, Map.Entry::getValue)
.contains(tuple("name", "kawhi"), tuple("age", 25));
softly.assertThat(map)
.extractingFromEntries(Map.Entry::getValue)
.contains("kawhi", 25);
// THEN
assertThat(softly.errorsCollected()).isEmpty();
}
@Test
void should_work_when_using_extracting_with_array() {
Name[] namesAsArray = { name("John", "Doe"), name("Jane", "Doe") };
try (AutoCloseableSoftAssertions softly = new AutoCloseableSoftAssertions()) {
softly.assertThat(namesAsArray)
.as("using extracting()")
.extracting("first")
.contains("John")
.contains("Jane");
softly.assertThat(namesAsArray)
.as("using extracting(Extractor)")
.extracting(Name::getFirst)
.contains("John")
.contains("Jane");
softly.assertThat(namesAsArray)
.as("using extracting(..., Class)")
.extracting("first", String.class)
.contains("John")
.contains("Jane");
softly.assertThat(namesAsArray)
.as("using extracting(...)")
.extracting("first", "last")
.contains(tuple("John", "Doe"))
.contains(tuple("Jane", "Doe"));
softly.assertThat(namesAsArray)
.as("using extractingResultOf(method, Class)")
.extractingResultOf("getFirst", String.class)
.contains("John")
.contains("Jane");
softly.assertThat(namesAsArray)
.as("using extractingResultOf(method)")
.extractingResultOf("getFirst")
.contains("John")
.contains("Jane");
}
}
@Test
void should_work_with_flat_extracting() {
// GIVEN
List<CartoonCharacter> characters = list(homer, fred);
CartoonCharacter[] charactersAsArray = characters.toArray(new CartoonCharacter[0]);
// WHEN
softly.assertThat(characters)
.as("using flatExtracting on Iterable")
.overridingErrorMessage("error message")
.flatExtracting(CartoonCharacter::getChildren)
.containsAnyOf(homer, fred)
.hasSize(123);
softly.assertThat(charactersAsArray)
.as("using flatExtracting on array")
.overridingErrorMessage("error message")
.flatExtracting(CartoonCharacter::getChildren)
.containsAnyOf(homer, fred)
.hasSize(456);
// THEN
List<Throwable> errorsCollected = softly.errorsCollected();
assertThat(errorsCollected).hasSize(4);
assertThat(errorsCollected.get(0)).hasMessage("[using flatExtracting on Iterable] error message");
assertThat(errorsCollected.get(1)).hasMessage("[using flatExtracting on Iterable] error message");
assertThat(errorsCollected.get(2)).hasMessage("[using flatExtracting on array] error message");
assertThat(errorsCollected.get(3)).hasMessage("[using flatExtracting on array] error message");
}
@Test
void should_work_with_flat_extracting_arrays() {
// GIVEN
CartoonCharacter[] charactersAsArray = array(homer, fred);
// WHEN
softly.assertThat(charactersAsArray)
.as("using flatExtracting on array")
.overridingErrorMessage("error message")
.flatExtracting(CartoonCharacter::getChildren)
.containsAnyOf(homer, fred)
.hasSize(456);
// THEN
List<Throwable> errorsCollected = softly.errorsCollected();
assertThat(errorsCollected).hasSize(2);
assertThat(errorsCollected.get(0)).hasMessage("[using flatExtracting on array] error message");
assertThat(errorsCollected.get(1)).hasMessage("[using flatExtracting on array] error message");
}
@Test
void should_collect_all_errors_when_using_extracting() {
// GIVEN
List<Name> names = list(name("John", "Doe"), name("Jane", "Doe"));
// WHEN
softly.assertThat(names)
.overridingErrorMessage("error 1")
.extracting("first")
.contains("gandalf")
.overridingErrorMessage("error 2")
.contains("frodo");
softly.assertThat(names)
.overridingErrorMessage("error 3")
.extracting("last")
.isEmpty();
// THEN
assertThat(softly.errorsCollected()).extracting(Throwable::getMessage)
.containsExactly("error 1", "error 2", "error 3");
}
@Test
void should_collect_all_errors_when_using_extracting_on_object() {
// GIVEN
TolkienCharacter frodo = TolkienCharacter.of("Frodo", 33, HOBBIT);
// WHEN
softly.assertThat(frodo)
.overridingErrorMessage("error 1")
.extracting("name")
.isEqualTo("Foo");
softly.assertThat(frodo)
.overridingErrorMessage("error 2")
.extracting("name", "age")
.contains("Frodo", 55);
softly.assertThat(frodo)
.overridingErrorMessage("error 3")
.extracting("name", as(STRING))
.startsWith("Bar");
softly.assertThat(frodo)
.overridingErrorMessage("error 4")
.extracting(TolkienCharacter::getName,
character -> character.age,
character -> character.getRace())
.containsExactly("Frodon", 33, HOBBIT);
softly.assertThat(frodo)
.overridingErrorMessage("error 5")
.extracting(TolkienCharacter::getName)
.isEqualTo("Foo");
softly.assertThat(frodo)
.overridingErrorMessage("error 6")
.extracting(TolkienCharacter::getName, as(STRING))
.startsWith("Bar");
// THEN
assertThat(softly.errorsCollected()).extracting(Throwable::getMessage)
.containsExactly("error 1", "error 2", "error 3", "error 4", "error 5", "error 6");
}
@Test
void should_collect_all_errors_when_using_flat_extracting() {
// GIVEN
List<CartoonCharacter> characters = list(homer, fred);
// WHEN
softly.assertThat(characters)
.overridingErrorMessage("error 1")
.flatExtracting(CartoonCharacter::getChildren)
.hasSize(0)
.overridingErrorMessage("error 2")
.isEmpty();
// THEN
assertThat(softly.errorsCollected()).extracting(Throwable::getMessage)
.containsExactly("error 1", "error 2");
}
@Test
void should_collect_all_errors_when_using_filtering() {
// GIVEN
LinkedHashSet<CartoonCharacter> dadsList = newLinkedHashSet(homer, fred);
CartoonCharacter[] dadsArray = array(homer, fred);
AtomicReferenceArray<CartoonCharacter> atomicDadsArray = new AtomicReferenceArray<>(dadsArray);
// WHEN
// iterables
softly.assertThat(dadsList)
.filteredOn("name", "Homer Simpson")
.withFailMessage("list: property filter error 1")
.hasSize(10)
.withFailMessage("list: property filter error 2")
.isEmpty();
softly.assertThat(dadsList)
.filteredOn("name", in("Homer Simpson"))
.withFailMessage("list: filter operator error 1")
.hasSize(10)
.withFailMessage("list: filter operator error 2")
.isEmpty();
softly.assertThat(dadsList)
.filteredOn(cartoonCharacter -> cartoonCharacter.getName().equals("Homer Simpson"))
.withFailMessage("list: predicate filter error 1")
.hasSize(10)
.withFailMessage("list: predicate filter error 2")
.isEmpty();
softly.assertThat(dadsList)
.filteredOn(CartoonCharacter::getName, "Homer Simpson")
.withFailMessage("list: function filter error 1")
.hasSize(10)
.withFailMessage("list: function filter error 2")
.isEmpty();
softly.assertThat(dadsList)
.filteredOn(new Condition<>(cartoonCharacter -> cartoonCharacter.getName().equals("Homer Simpson"), "startsWith Jo"))
.withFailMessage("list: Condition filter error 1")
.hasSize(10)
.withFailMessage("list: Condition filter error 2")
.isEmpty();
softly.assertThat(dadsList)
.filteredOnNull("name")
.withFailMessage("list: null filter error 1")
.hasSize(10)
.withFailMessage("list: null filter error 2")
.isNotEmpty();
softly.assertThat(dadsList)
.filteredOnAssertions(cartoonCharacter -> cartoonCharacter.getName().equals("Homer Simpson"))
.withFailMessage("list: assertion filter error 1")
.hasSize(10)
.withFailMessage("list: assertion filter error 2")
.isEmpty();
// array
softly.assertThat(dadsArray)
.filteredOn("name", "Homer Simpson")
.withFailMessage("array: property filter error 1")
.hasSize(10)
.withFailMessage("array: property filter error 2")
.isEmpty();
softly.assertThat(dadsArray)
.filteredOn("name", in("Homer Simpson"))
.withFailMessage("array: filter operator error 1")
.hasSize(10)
.withFailMessage("array: filter operator error 2")
.isEmpty();
softly.assertThat(dadsArray)
.filteredOn(cartoonCharacter -> cartoonCharacter.getName().equals("Homer Simpson"))
.withFailMessage("array: predicate filter error 1")
.hasSize(10)
.withFailMessage("array: predicate filter error 2")
.isEmpty();
softly.assertThat(dadsArray)
.filteredOn(CartoonCharacter::getName, "Homer Simpson")
.withFailMessage("array: function filter error 1")
.hasSize(10)
.withFailMessage("array: function filter error 2")
.isEmpty();
softly.assertThat(dadsArray)
.filteredOn(new Condition<>(cartoonCharacter -> cartoonCharacter.getName().equals("Homer Simpson"), "startsWith Jo"))
.withFailMessage("array: Condition filter error 1")
.hasSize(10)
.withFailMessage("array: Condition filter error 2")
.isEmpty();
softly.assertThat(dadsArray)
.filteredOnNull("name")
.withFailMessage("array: null filter error 1")
.hasSize(10)
.withFailMessage("array: null filter error 2")
.isNotEmpty();
softly.assertThat(dadsArray)
.filteredOnAssertions(cartoonCharacter -> cartoonCharacter.getName().equals("Homer Simpson"))
.withFailMessage("array: assertion filter error 1")
.hasSize(10)
.withFailMessage("array: assertion filter error 2")
.isEmpty();
// atomic array
softly.assertThat(atomicDadsArray)
.filteredOn("name", "Homer Simpson")
.withFailMessage("atomic: property filter error 1")
.hasSize(10)
.withFailMessage("atomic: property filter error 2")
.isEmpty();
softly.assertThat(atomicDadsArray)
.filteredOn("name", in("Homer Simpson"))
.withFailMessage("atomic: filter operator error 1")
.hasSize(10)
.withFailMessage("atomic: filter operator error 2")
.isEmpty();
softly.assertThat(atomicDadsArray)
.filteredOn(cartoonCharacter -> cartoonCharacter.getName().equals("Homer Simpson"))
.withFailMessage("atomic: predicate filter error 1")
.hasSize(10)
.withFailMessage("atomic: predicate filter error 2")
.isEmpty();
softly.assertThat(atomicDadsArray)
.filteredOn(CartoonCharacter::getName, "Homer Simpson")
.withFailMessage("atomic: function filter error 1")
.hasSize(10)
.withFailMessage("atomic: function filter error 2")
.isEmpty();
softly.assertThat(atomicDadsArray)
.filteredOn(new Condition<>(cartoonCharacter -> cartoonCharacter.getName().equals("Homer Simpson"), "startsWith Jo"))
.withFailMessage("atomic: Condition filter error 1")
.hasSize(10)
.withFailMessage("atomic: Condition filter error 2")
.isEmpty();
softly.assertThat(atomicDadsArray)
.filteredOnNull("name")
.withFailMessage("atomic: null filter error 1")
.hasSize(10)
.withFailMessage("atomic: null filter error 2")
.isNotEmpty();
// THEN
assertThat(softly.errorsCollected()).extracting(Throwable::getMessage)
.containsExactly("list: property filter error 1", "list: property filter error 2",
"list: filter operator error 1", "list: filter operator error 2",
"list: predicate filter error 1", "list: predicate filter error 2",
"list: function filter error 1", "list: function filter error 2",
"list: Condition filter error 1", "list: Condition filter error 2",
"list: null filter error 1", "list: null filter error 2",
"list: assertion filter error 1", "list: assertion filter error 2",
"array: property filter error 1", "array: property filter error 2",
"array: filter operator error 1", "array: filter operator error 2",
"array: predicate filter error 1", "array: predicate filter error 2",
"array: function filter error 1", "array: function filter error 2",
"array: Condition filter error 1", "array: Condition filter error 2",
"array: null filter error 1", "array: null filter error 2",
"array: assertion filter error 1", "array: assertion filter error 2",
"atomic: property filter error 1", "atomic: property filter error 2",
"atomic: filter operator error 1", "atomic: filter operator error 2",
"atomic: predicate filter error 1", "atomic: predicate filter error 2",
"atomic: function filter error 1", "atomic: function filter error 2",
"atomic: Condition filter error 1", "atomic: Condition filter error 2",
"atomic: null filter error 1", "atomic: null filter error 2");
}
@Test
void should_work_with_comparable() {
// GIVEN
ComparableExample example1 = new ComparableExample(0);
ComparableExample example2 = new ComparableExample(0);
ComparableExample example3 = new ComparableExample(123);
// WHEN
softly.assertThat(example1).isEqualByComparingTo(example2);
softly.assertThat(example1).isEqualByComparingTo(example3);
// THEN
List<Throwable> errorsCollected = softly.errorsCollected();
assertThat(errorsCollected).singleElement(as(THROWABLE))
.hasMessageContaining("123");
}
@Test
void should_work_with_stream() {
// WHEN
softly.assertThat(Stream.of("a", "b", "c")).contains("a", "foo");
softly.assertThat(IntStream.of(1, 2, 3)).as("IntStream").contains(2, 4, 6);
softly.assertThat(LongStream.of(1, 2, 3)).contains(-1L, -2L, -3L);
softly.assertThat(DoubleStream.of(1, 2, 3)).contains(10.0, 20.0, 30.0);
// THEN
List<Throwable> errorsCollected = softly.errorsCollected();
assertThat(errorsCollected).hasSize(4);
assertThat(errorsCollected.get(0)).hasMessageContaining("foo");
assertThat(errorsCollected.get(1)).hasMessageContaining("6")
.hasMessageContaining("IntStream");
assertThat(errorsCollected.get(2)).hasMessageContaining("-3");
assertThat(errorsCollected.get(3)).hasMessageContaining("30.0");
}
@Test
void should_work_with_predicate() {
// GIVEN
Predicate<String> lowercasePredicate = s -> s.equals(s.toLowerCase());
// WHEN
softly.assertThat(lowercasePredicate).as("abc").accepts("a", "b", "c");
softly.assertThat(lowercasePredicate).as("abC").accepts("a", "b", "C");
// THEN
assertThat(softly.errorsCollected()).hasSize(1);
assertThat(softly.errorsCollected().get(0)).hasMessageContaining("abC")
.hasMessageContaining("C");
}
@Test
void should_work_with_optional() {
// GIVEN
Optional<String> optional = Optional.of("Gandalf");
// WHEN
softly.assertThat(optional)
.contains("Gandalf");
softly.assertThat(optional)
.map(String::length)
.contains(7);
softly.assertThat(optional)
.get()
.isEqualTo("Gandalf");
softly.assertThat(optional)
.get(as(STRING))
.startsWith("Gan");
// THEN
softly.assertAll();
}
@Test
void should_propagate_AssertionError_from_nested_proxied_calls() {
// the nested proxied call to isNotEmpty() throw an Assertion error that must be propagated to the caller.
softly.assertThat(emptyList()).first();
// the nested proxied call to isNotEmpty() throw an Assertion error that must be propagated to the caller.
softly.assertThat(emptyList()).first(as(STRING));
// the nested proxied call to isNotEmpty() throw an Assertion error that must be propagated to the caller.
softly.assertThat(emptyList()).element(0);
// the nested proxied call to isNotEmpty() throw an Assertion error that must be propagated to the caller.
softly.assertThat(emptyList()).element(0, as(STRING));
// the nested proxied call to isNotEmpty() throw an Assertion error that must be propagated to the caller.
softly.assertThat(emptyList()).elements(0, 1, 2);
// the nested proxied call to checkIndexValidity throw an Assertion error that must be propagated to the caller.
softly.assertThat(list("a", "b")).elements(0, 5);
// the nested proxied call to isNotEmpty() throw an Assertion error that must be propagated to the caller.
softly.assertThat(emptyList()).last();
// the nested proxied call to isNotEmpty() throw an Assertion error that must be propagated to the caller.
softly.assertThat(emptyList()).last(as(STRING));
// the nested proxied call to assertHasSize() throw an Assertion error that must be propagated to the caller.
softly.assertThat(emptyList()).singleElement();
// the nested proxied call to assertHasSize() throw an Assertion error that must be propagated to the caller.
softly.assertThat(emptyList()).singleElement(as(STRING));
// nested proxied call to throwAssertionError when checking that is optional is present
softly.assertThat(Optional.empty()).contains("Foo");
// nested proxied call to isNotNull
softly.assertThat((Predicate<String>) null).accepts("a", "b", "c");
// nested proxied call to isCompleted
softly.assertThat(new CompletableFuture<String>()).isCompletedWithValue("done");
// nested proxied call to isEqualTo
softly.assertThat(Duration.ofDays(1)).isZero();
// nested proxied call to isLessThan
softly.assertThat(Duration.ofDays(1)).isNegative();
// nested proxied call to isGreaterThan
softly.assertThat(Duration.ofDays(-1)).isPositive();
// it must be caught by softly.assertAll()
assertThat(softly.errorsCollected()).hasSize(16);
}
@Test
void check_477_bugfix() {
// GIVEN
TolkienCharacter frodo = TolkienCharacter.of("frodo", 33, HOBBIT);
TolkienCharacter samnullGamgee = null;
TolkienSoftAssertions softly = new TolkienSoftAssertions();
// WHEN
softly.assertThat(frodo).hasAge(10); // Expect failure - age will be 0 due to not being initialized.
softly.assertThat(samnullGamgee).hasAge(11); // Expect failure - argument is null.
// THEN
assertThat(softly.errorsCollected()).hasSize(2);
}
public static class TolkienSoftAssertions extends SoftAssertions {
public TolkienCharacterAssert assertThat(TolkienCharacter actual) {
return proxy(TolkienCharacterAssert.class, TolkienCharacter.class, actual);
}
}
@Test