-
-
Notifications
You must be signed in to change notification settings - Fork 682
/
AbstractAssert.java
1184 lines (1079 loc) · 48.7 KB
/
AbstractAssert.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-2024 the original author or authors.
*/
package org.assertj.core.api;
import static java.lang.String.format;
import static java.util.Arrays.stream;
import static java.util.Objects.requireNonNull;
import static java.util.stream.Collectors.toList;
import static org.assertj.core.description.Description.mostRelevantDescription;
import static org.assertj.core.error.ShouldMatch.shouldMatch;
import static org.assertj.core.error.ShouldNotBeNull.shouldNotBeNull;
import static org.assertj.core.extractor.Extractors.byName;
import static org.assertj.core.extractor.Extractors.extractedDescriptionOf;
import static org.assertj.core.util.Lists.list;
import static org.assertj.core.util.Preconditions.checkArgument;
import static org.assertj.core.util.Strings.formatIfArgs;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import org.assertj.core.api.recursive.assertion.RecursiveAssertionConfiguration;
import org.assertj.core.api.recursive.comparison.RecursiveComparisonConfiguration;
import org.assertj.core.configuration.ConfigurationProvider;
import org.assertj.core.description.Description;
import org.assertj.core.error.AssertionErrorCreator;
import org.assertj.core.error.BasicErrorMessageFactory;
import org.assertj.core.error.ErrorMessageFactory;
import org.assertj.core.error.MessageFormatter;
import org.assertj.core.internal.ComparatorBasedComparisonStrategy;
import org.assertj.core.internal.ComparisonStrategy;
import org.assertj.core.internal.Conditions;
import org.assertj.core.internal.Failures;
import org.assertj.core.internal.Objects;
import org.assertj.core.presentation.PredicateDescription;
import org.assertj.core.presentation.Representation;
import org.assertj.core.util.CheckReturnValue;
import org.assertj.core.util.VisibleForTesting;
/**
* Base class for all assertions.
*
* @param <SELF> the "self" type of this assertion class. Please read "<a href="http://bit.ly/1IZIRcY"
* target="_blank">Emulating 'self types' using Java Generics to simplify fluent API implementation</a>"
* for more details.
* @param <ACTUAL> the type of the "actual" value.
*
* @author Alex Ruiz
* @author Joel Costigliola
* @author Mikhail Mazursky
* @author Nicolas François
*/
public abstract class AbstractAssert<SELF extends AbstractAssert<SELF, ACTUAL>, ACTUAL> implements Assert<SELF, ACTUAL> {
// https://github.com/assertj/assertj/issues/1128
public static boolean throwUnsupportedExceptionOnEquals = true;
private static final String ORG_ASSERTJ = "org.assert";
protected Objects objects = Objects.instance();
@VisibleForTesting
Conditions conditions = Conditions.instance();
@VisibleForTesting
public WritableAssertionInfo info;
// visibility is protected to allow us write custom assertions that need access to actual
protected final ACTUAL actual;
protected final SELF myself;
@VisibleForTesting
// = ConfigurationProvider.CONFIGURATION_PROVIDER.representation(); ?
static Representation customRepresentation = null;
@VisibleForTesting
AssertionErrorCreator assertionErrorCreator;
@VisibleForTesting
static boolean printAssertionsDescription;
private static Consumer<Description> descriptionConsumer;
// we prefer not to use Class<? extends S> selfType because it would force inherited
// constructor to cast with a compiler warning
// let's keep compiler warning internal (when we can) and not expose them to our end users.
@SuppressWarnings("unchecked")
protected AbstractAssert(ACTUAL actual, Class<?> selfType) {
myself = (SELF) selfType.cast(this);
this.actual = actual;
info = new WritableAssertionInfo(customRepresentation);
assertionErrorCreator = new AssertionErrorCreator();
}
/**
* Exposes the {@link WritableAssertionInfo} used in the current assertion for better extensibility.<br> When writing
* your own assertion class, you can use the returned {@link WritableAssertionInfo} to change the error message and
* still keep the description set by the assertion user.
*
* @return the {@link WritableAssertionInfo} used in the current assertion
*/
public WritableAssertionInfo getWritableAssertionInfo() {
return info;
}
/**
* Throw an assertion error based on information in this assertion. Equivalent to:
* <pre><code class='java'>throw failure(errorMessage, arguments);</code></pre>
* <p>
* This method is a thin wrapper around {@link #failure(String, Object...) failure()} - see that method for a more detailed
* description.
* <p>
* Note that generally speaking, using {@link #failure(String, Object...) failure()} directly is preferable to using this
* wrapper method, as the compiler and other code analysis tools will be able to tell that the statement will never return
* normally and respond appropriately.
*
* @param errorMessage the error message to format
* @param arguments the arguments referenced by the format specifiers in the errorMessage string.
* @see #failWithActualExpectedAndMessage(Object, Object, String, Object...)
* @see #failure(String, Object...)
*/
protected void failWithMessage(String errorMessage, Object... arguments) {
throw failure(errorMessage, arguments);
}
/**
* Generate a custom assertion error using the information in this assertion.
* <p>
* This is a utility method to ease writing custom assertions classes using {@link String#format(String, Object...)} specifiers
* in error message.
* <p>
* Moreover, this method honors any description set with {@link #as(String, Object...)} or overridden error message
* defined by the user with {@link #overridingErrorMessage(String, Object...)}.
* <p>
* Example:
* <pre><code class='java'> public TolkienCharacterAssert hasName(String name) {
* // check that actual TolkienCharacter we want to make assertions on is not null.
* isNotNull();
*
* // check condition
* if (!actual.getName().equals(name)) {
* failWithMessage("Expected character's name to be <%s> but was <%s>", name, actual.getName());
* }
*
* // return the current assertion for method chaining
* return this;
* }</code></pre>
*
* @param errorMessage the error message to format
* @param arguments the arguments referenced by the format specifiers in the errorMessage string.
* @see #failureWithActualExpected(Object, Object, String, Object...)
* @see #failWithMessage(String, Object...)
* @return The generated assertion error.
*/
protected AssertionError failure(String errorMessage, Object... arguments) {
AssertionError assertionError = Failures.instance().failureIfErrorMessageIsOverridden(info);
if (assertionError == null) {
// error message was not overridden, build it.
String description = MessageFormatter.instance().format(info.description(), info.representation(), "");
assertionError = new AssertionError(description + format(errorMessage, arguments));
}
Failures.instance().removeAssertJRelatedElementsFromStackTraceIfNeeded(assertionError);
removeCustomAssertRelatedElementsFromStackTraceIfNeeded(assertionError);
return assertionError;
}
/**
* Throw an assertion error based on information in this assertion. Equivalent to:
* <pre><code class='java'>throw failureWithActualExpected(actual, expected, errorMessageFormat, arguments);</code></pre>
* <p>
* This method is a thin wrapper around {@link #failureWithActualExpected(Object, Object, String, Object...) failureWithActualExpected()} -
* see that method for a more detailed description. Note that generally speaking, using
* {@link #failureWithActualExpected(Object, Object, String, Object...) failureWithActualExpected()} directly is
* preferable to using this wrapper method, as the compiler and other code analysis tools will be able to tell that the
* statement will never return normally and respond appropriately.
*
* @param actual the actual object that was found during the test
* @param expected the object that was expected
* @param errorMessageFormat the error message to format
* @param arguments the arguments referenced by the format specifiers in the errorMessage string.
* @see #failWithMessage(String, Object...)
* @see #failureWithActualExpected(Object, Object, String, Object...)
*/
protected void failWithActualExpectedAndMessage(Object actual, Object expected, String errorMessageFormat,
Object... arguments) {
throw failureWithActualExpected(actual, expected, errorMessageFormat, arguments);
}
/**
* Generate a custom assertion error using the information in this assertion, using the given actual and expected values.
* <p>
* This is a utility method to ease writing custom assertions classes using {@link String#format(String, Object...)} specifiers
* in error message with actual and expected values.
* <p>
* Moreover, this method honors any description set with {@link #as(String, Object...)} or overridden error message
* defined by the user with {@link #overridingErrorMessage(String, Object...)}.
* <p>
* This method also sets the "actual" and "expected" fields of the assertion if available (eg, if OpenTest4J is on the path).
* This aids IDEs to produce visual diffs of the resulting values.
* <p>
* Example :
* <pre><code class='java'> public TolkienCharacterAssert hasName(String name) {
* // check that actual TolkienCharacter we want to make assertions on is not null.
* isNotNull();
*
* // check condition
* if (!actual.getName().equals(name)) {
* throw failureWithActualExpected(actual.getName(), name, "Expected character's name to be <%s> but was <%s>", name, actual.getName());
* }
*
* // return the current assertion for method chaining
* return this;
* }</code></pre>
*
* @param actual the actual object that was found during the test
* @param expected the object that was expected
* @param errorMessageFormat the error message to format
* @param arguments the arguments referenced by the format specifiers in the errorMessage string.
* @return The generated assertion error.
* @see #failure(String, Object...)
* @see #failWithActualExpectedAndMessage(Object, Object, String, Object...)
*/
protected AssertionError failureWithActualExpected(Object actual, Object expected, String errorMessageFormat,
Object... arguments) {
String errorMessage = Optional.ofNullable(info.overridingErrorMessage())
.orElse(format(errorMessageFormat, arguments));
String description = MessageFormatter.instance().format(info.description(), info.representation(), errorMessage);
AssertionError assertionError = assertionErrorCreator.assertionError(description, actual, expected, info.representation());
Failures.instance().removeAssertJRelatedElementsFromStackTraceIfNeeded(assertionError);
removeCustomAssertRelatedElementsFromStackTraceIfNeeded(assertionError);
return assertionError;
}
/**
* Utility method to throw an {@link AssertionError} given a {@link BasicErrorMessageFactory}.
* <p>
* Instead of writing ...
*
* <pre><code class='java'> throw Failures.instance().failure(info, ShouldBePresent.shouldBePresent());</code></pre>
* ... you can simply write :
*
* <pre><code class='java'> throwAssertionError(info, ShouldBePresent.shouldBePresent());</code></pre>
*
* @param errorMessageFactory used to define the error message.
* @throws AssertionError with a message corresponding to the given {@link BasicErrorMessageFactory}.
*/
protected void throwAssertionError(ErrorMessageFactory errorMessageFactory) {
throw assertionError(errorMessageFactory);
}
protected AssertionError assertionError(ErrorMessageFactory errorMessageFactory) {
AssertionError failure = Failures.instance().failure(info, errorMessageFactory);
removeCustomAssertRelatedElementsFromStackTraceIfNeeded(failure);
return failure;
}
private void removeCustomAssertRelatedElementsFromStackTraceIfNeeded(AssertionError assertionError) {
if (!Failures.instance().isRemoveAssertJRelatedElementsFromStackTrace()) return;
if (isAssertjAssertClass()) return;
StackTraceElement[] newStackTrace = Arrays.stream(assertionError.getStackTrace())
.filter(element -> !isElementOfCustomAssert(element))
.toArray(StackTraceElement[]::new);
assertionError.setStackTrace(newStackTrace);
}
private boolean isAssertjAssertClass() {
return getClass().getName().startsWith(ORG_ASSERTJ);
}
protected boolean isElementOfCustomAssert(StackTraceElement stackTraceElement) {
Class<?> currentAssertClass = getClass();
while (currentAssertClass != AbstractAssert.class) {
if (stackTraceElement.getClassName().equals(currentAssertClass.getName())) return true;
currentAssertClass = currentAssertClass.getSuperclass();
}
return false;
}
/**
* Use hexadecimal object representation instead of standard representation in error messages.
* <p>
* It can be useful when comparing UNICODE characters - many unicode chars have duplicate characters assigned, it is
* thus impossible to find differences from the standard error message:
* <p>
* With standard message:
* <pre><code class='java'> assertThat("µµµ").contains("μμμ");
*
* java.lang.AssertionError:
* Expecting:
* <"µµµ">
* to contain:
* <"μμμ"></code></pre>
*
* With Hexadecimal message:
* <pre><code class='java'> assertThat("µµµ").inHexadecimal().contains("μμμ");
*
* java.lang.AssertionError:
* Expecting:
* <"['00B5', '00B5', '00B5']">
* to contain:
* <"['03BC', '03BC', '03BC']"></code></pre>
*
* @return {@code this} assertion object.
*/
@CheckReturnValue
protected SELF inHexadecimal() {
info.useHexadecimalRepresentation();
return myself;
}
/**
* Use binary object representation instead of standard representation in error messages.
* <p>
* Example:
* <pre><code class='java'> assertThat(1).inBinary().isEqualTo(2);
*
* org.junit.ComparisonFailure:
* Expected :0b00000000_00000000_00000000_00000010
* Actual :0b00000000_00000000_00000000_00000001</code></pre>
*
* @return {@code this} assertion object.
*/
@CheckReturnValue
protected SELF inBinary() {
info.useBinaryRepresentation();
return myself;
}
/** {@inheritDoc} */
@Override
@CheckReturnValue
public SELF describedAs(Description description) {
info.description(description);
if (printAssertionsDescription) printDescriptionText();
if (descriptionConsumer != null) descriptionConsumer.accept(description);
return myself;
}
private void printDescriptionText() {
String descriptionText = info.descriptionText();
if (!descriptionText.isEmpty()) System.out.println(descriptionText);
}
/** {@inheritDoc} */
@Override
public SELF isEqualTo(Object expected) {
if (actual instanceof AbstractAssert<?, ?> && throwUnsupportedExceptionOnEquals) {
throw new UnsupportedOperationException("Attempted to compare an assertion object to another object using 'isEqualTo'. "
+ "This is not supported. Perhaps you meant 'isSameAs' instead?");
}
objects.assertEqual(info, actual, expected);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF isNotEqualTo(Object other) {
if (actual instanceof AbstractAssert<?, ?> && throwUnsupportedExceptionOnEquals) {
throw new UnsupportedOperationException("Attempted to compare an assertion object to another object using 'isNotEqualTo'. "
+ "This is not supported. Perhaps you meant 'isNotSameAs' instead?");
}
objects.assertNotEqual(info, actual, other);
return myself;
}
/** {@inheritDoc} */
@Override
public void isNull() {
objects.assertNull(info, actual);
}
/** {@inheritDoc} */
@Override
public SELF isNotNull() {
objects.assertNotNull(info, actual);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF isSameAs(Object expected) {
objects.assertSame(info, actual, expected);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF isNotSameAs(Object other) {
objects.assertNotSame(info, actual, other);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF isIn(Object... values) {
objects.assertIsIn(info, actual, values);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF isNotIn(Object... values) {
objects.assertIsNotIn(info, actual, values);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF isIn(Iterable<?> values) {
objects.assertIsIn(info, actual, values);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF isNotIn(Iterable<?> values) {
objects.assertIsNotIn(info, actual, values);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF is(Condition<? super ACTUAL> condition) {
conditions.assertIs(info, actual, condition);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF isNot(Condition<? super ACTUAL> condition) {
conditions.assertIsNot(info, actual, condition);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF has(Condition<? super ACTUAL> condition) {
conditions.assertHas(info, actual, condition);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF doesNotHave(Condition<? super ACTUAL> condition) {
conditions.assertDoesNotHave(info, actual, condition);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF satisfies(Condition<? super ACTUAL> condition) {
conditions.assertSatisfies(info, actual, condition);
return myself;
}
/** {@inheritDoc} */
@SuppressWarnings("unchecked")
@Override
@CheckReturnValue
public <ASSERT extends AbstractAssert<?, ?>> ASSERT asInstanceOf(InstanceOfAssertFactory<?, ASSERT> instanceOfAssertFactory) {
requireNonNull(instanceOfAssertFactory, shouldNotBeNull("instanceOfAssertFactory")::create);
objects.assertIsInstanceOf(info, actual, instanceOfAssertFactory.getRawClass());
return (ASSERT) instanceOfAssertFactory.createAssert(actual).withAssertionState(myself);
}
/** {@inheritDoc} */
@Override
public SELF isInstanceOf(Class<?> type) {
objects.assertIsInstanceOf(info, actual, type);
return myself;
}
/** {@inheritDoc} */
@SuppressWarnings("unchecked")
@Override
public <T> SELF isInstanceOfSatisfying(Class<T> type, Consumer<T> requirements) {
objects.assertIsInstanceOf(info, actual, type);
requireNonNull(requirements, "The Consumer<T> expressing the assertions requirements must not be null");
requirements.accept((T) actual);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF isInstanceOfAny(Class<?>... types) {
objects.assertIsInstanceOfAny(info, actual, types);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF isNotInstanceOf(Class<?> type) {
objects.assertIsNotInstanceOf(info, actual, type);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF isNotInstanceOfAny(Class<?>... types) {
objects.assertIsNotInstanceOfAny(info, actual, types);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF hasSameClassAs(Object other) {
objects.assertHasSameClassAs(info, actual, other);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF hasToString(String expectedToString) {
objects.assertHasToString(info, actual, expectedToString);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF hasToString(String expectedStringTemplate, Object... args) {
requireNonNull(expectedStringTemplate, "The expectedStringTemplate must not be null");
return hasToString(format(expectedStringTemplate, args));
}
/** {@inheritDoc} */
@Override
public SELF doesNotHaveToString(String otherToString) {
objects.assertDoesNotHaveToString(info, actual, otherToString);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF doesNotHaveToString(String expectedStringTemplate, Object... args) {
requireNonNull(expectedStringTemplate, "The expectedStringTemplate must not be null");
return doesNotHaveToString(format(expectedStringTemplate, args));
}
/** {@inheritDoc} */
@Override
public SELF doesNotHaveSameClassAs(Object other) {
objects.assertDoesNotHaveSameClassAs(info, actual, other);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF isExactlyInstanceOf(Class<?> type) {
objects.assertIsExactlyInstanceOf(info, actual, type);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF isNotExactlyInstanceOf(Class<?> type) {
objects.assertIsNotExactlyInstanceOf(info, actual, type);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF isOfAnyClassIn(Class<?>... types) {
objects.assertIsOfAnyClassIn(info, actual, types);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF isNotOfAnyClassIn(Class<?>... types) {
objects.assertIsNotOfAnyClassIn(info, actual, types);
return myself;
}
/**
* {@inheritDoc}
* @deprecated use {@link #asInstanceOf(InstanceOfAssertFactory) asInstanceOf(InstanceOfAssertFactories.LIST)} instead
*/
@Deprecated
@Override
@CheckReturnValue
public AbstractListAssert<?, List<?>, Object, ObjectAssert<Object>> asList() {
return asInstanceOf(InstanceOfAssertFactories.LIST);
}
/** {@inheritDoc} */
@Override
@CheckReturnValue
public AbstractStringAssert<?> asString() {
objects.assertNotNull(info, actual);
return Assertions.assertThat(actual.toString());
}
/**
* The description of this assertion set with {@link #describedAs(String, Object...)} or
* {@link #describedAs(Description)}.
*
* @return the description String representation of this assertion.
*/
public String descriptionText() {
return info.descriptionText();
}
/**
* Overrides AssertJ default error message by the given one.
* <p>
* You must set it <b>before</b> calling the assertion otherwise it is ignored as the failing assertion breaks
* the chained call by throwing an AssertionError.
* <p>
* The new error message is built using {@link String#format(String, Object...)} if you provide args parameter (if you
* don't, the error message is taken as it is).
* <p>
* Example :
* <pre><code class='java'>assertThat(player.isRookie()).overridingErrorMessage("Expecting Player <%s> to be a rookie but was not.", player)
* .isTrue();</code></pre>
*
* @param newErrorMessage the error message that will replace the default one provided by Assertj.
* @param args the args used to fill error message as in {@link String#format(String, Object...)}.
* @return this assertion object.
*/
@CheckReturnValue
public SELF overridingErrorMessage(String newErrorMessage, Object... args) {
info.overridingErrorMessage(formatIfArgs(newErrorMessage, args));
return myself;
}
/**
* Overrides AssertJ default error message by the given one.
* <p>
* The new error message is only built if the assertion fails (by consuming the given supplier), this is useful if building messages is expensive.
* <p>
* You must set the message <b>before</b> calling the assertion otherwise it is ignored as the failing assertion breaks
* the call chain by throwing an {@link AssertionError}.
* <p>
* Example :
* <pre><code class='java'>assertThat(player.isRookie()).overridingErrorMessage(() -> "Expecting Player to be a rookie but was not.")
* .isTrue();</code></pre>
*
* @param supplier the supplier supplies error message that will replace the default one provided by Assertj.
* @return this assertion object.
*/
@CheckReturnValue
public SELF overridingErrorMessage(Supplier<String> supplier) {
info.overridingErrorMessage(supplier);
return myself;
}
/**
* Alternative method for {@link AbstractAssert#overridingErrorMessage}
* <p>
* You must set it <b>before</b> calling the assertion otherwise it is ignored as the failing assertion breaks
* the chained call by throwing an AssertionError.
* <p>
* Example:
* <pre><code class='java'>assertThat(player.isRookie()).withFailMessage("Expecting Player <%s> to be a rookie but was not.", player)
* .isTrue();</code></pre>
* @param newErrorMessage the error message that will replace the default one provided by Assertj.
* @param args the args used to fill error message as in {@link String#format(String, Object...)}.
* @return this assertion object.
*/
@CheckReturnValue
public SELF withFailMessage(String newErrorMessage, Object... args) {
return overridingErrorMessage(newErrorMessage, args);
}
/**
* Alternative method for {@link AbstractAssert#overridingErrorMessage}
* <p>
* The new error message is only built if the assertion fails (by consuming the given supplier), this is useful if building messages is expensive.
* <p>
* You must set the message <b>before</b> calling the assertion otherwise it is ignored as the failing assertion breaks
* the call chain by throwing an {@link AssertionError}.
* <p>
* Example:
* <pre><code class='java'>assertThat(player.isRookie()).withFailMessage(() -> "Expecting Player to be a rookie but was not.")
* .isTrue();</code></pre>
* @param supplier the supplier supplies error message that will replace the default one provided by Assertj.
* @return this assertion object.
*/
@CheckReturnValue
public SELF withFailMessage(Supplier<String> supplier) {
return overridingErrorMessage(supplier);
}
/** {@inheritDoc} */
@Override
@CheckReturnValue
public SELF usingComparator(Comparator<? super ACTUAL> customComparator) {
return usingComparator(customComparator, null);
}
/** {@inheritDoc} */
@Override
@CheckReturnValue
public SELF usingComparator(Comparator<? super ACTUAL> customComparator, String customComparatorDescription) {
// using a specific strategy to compare actual with other objects.
this.objects = new Objects(new ComparatorBasedComparisonStrategy(customComparator, customComparatorDescription));
return myself;
}
/** {@inheritDoc} */
@Override
@CheckReturnValue
public SELF usingDefaultComparator() {
// fall back to default strategy to compare actual with other objects.
this.objects = Objects.instance();
return myself;
}
/** {@inheritDoc} */
@Override
@CheckReturnValue
public SELF withThreadDumpOnError() {
Failures.instance().enablePrintThreadDump();
return myself;
}
/** {@inheritDoc} */
@Override
@CheckReturnValue
public SELF withRepresentation(Representation representation) {
info.useRepresentation(representation);
return myself;
}
/**
* {@inheritDoc}
*
* @deprecated use {@link #isEqualTo} instead
*
* @throws UnsupportedOperationException if this method is called.
*/
@Override
@Deprecated
public boolean equals(Object obj) {
if (throwUnsupportedExceptionOnEquals) {
throw new UnsupportedOperationException("'equals' is not supported... maybe you intended to call 'isEqualTo'");
}
return super.equals(obj);
}
/**
* Always returns 1.
*
* @return 1.
*/
@Override
public int hashCode() {
return 1;
}
/**
* Verifies that the actual object matches the given predicate.
* <p>
* Example :
*
* <pre><code class='java'> assertThat(player).matches(p -> p.isRookie());</code></pre>
*
* @param predicate the {@link Predicate} to match
* @return {@code this} assertion object.
* @throws AssertionError if {@code actual} does not match the given {@link Predicate}.
* @throws NullPointerException if given {@link Predicate} is null.
*/
public SELF matches(Predicate<? super ACTUAL> predicate) {
// use default PredicateDescription
return matches(predicate, PredicateDescription.GIVEN);
}
/**
* Verifies that the actual object matches the given predicate, the predicate description is used to get an
* informative error message.
* <p>
* Example :
*
* <pre><code class='java'> assertThat(player).matches(p -> p.isRookie(), "is rookie");</code></pre>
*
* The error message contains the predicate description, if the previous assertion fails, it will be:
*
* <pre><code class='java'> Expecting:
* <player>
* to match 'is rookie' predicate.</code></pre>
*
* @param predicate the {@link Predicate} to match
* @param predicateDescription a description of the {@link Predicate} used in the error message
* @return {@code this} assertion object.
* @throws AssertionError if {@code actual} does not match the given {@link Predicate}.
* @throws NullPointerException if given {@link Predicate} is null.
* @throws NullPointerException if given predicateDescription is null.
*/
public SELF matches(Predicate<? super ACTUAL> predicate, String predicateDescription) {
return matches(predicate, new PredicateDescription(predicateDescription));
}
/**
* Verifies that the actual object satisfied the given requirements expressed as {@link Consumer}s.
* <p>
* This is useful to perform a group of assertions on a single object, each passed assertion is evaluated and all failures are reported (to be precise each assertion can lead to one failure max).
* <p>
* Grouping assertions example :
* <pre><code class='java'> // second constructor parameter is the light saber color
* Jedi yoda = new Jedi("Yoda", "Green");
* Jedi luke = new Jedi("Luke Skywalker", "Green");
*
* Consumer<Jedi> redLightSaber = jedi -> assertThat(jedi.getLightSaberColor()).isEqualTo("Red");
* Consumer<Jedi> greenLightSaber = jedi -> assertThat(jedi.getLightSaberColor()).isEqualTo("Green");
* Consumer<Jedi> notDarth = jedi -> assertThat(jedi.getName()).doesNotContain("Darth");
* Consumer<Jedi> darth = jedi -> assertThat(jedi.getName()).contains("Darth");
*
* // assertions succeed:
* assertThat(yoda).satisfies(greenLightSaber);
* assertThat(luke).satisfies(greenLightSaber, notDarth);
*
* // assertions fail:
* Jedi vader = new Jedi("Darth Vader", "Red");
* assertThat(vader).satisfies(greenLightSaber);
* assertThat(vader).satisfies(darth, greenLightSaber);
* assertThat(vader).satisfies(greenLightSaber, notDarth);</code></pre>
* <p>
* In the following example, {@code satisfies} prevents the need to define a local variable in order to run multiple assertions:
* <pre><code class='java'> // no need to define team.getPlayers().get(0).getStats() as a local variable
* assertThat(team.getPlayers().get(0).getStats()).satisfies(stats -> assertThat(stats.pointPerGame).isGreaterThan(25.7),
* stats -> assertThat(stats.assistsPerGame).isGreaterThan(7.2),
* stats -> assertThat(stats.reboundsPerGame).isBetween(9, 12));</code></pre>
*
* @param requirements to assert on the actual object - must not be null.
* @return this assertion object.
*
* @throws NullPointerException if any given Consumer is null
*/
@SafeVarargs
public final SELF satisfies(Consumer<? super ACTUAL>... requirements) {
return satisfiesForProxy(requirements);
}
/**
* Verifies that the actual object satisfied the given requirements expressed as {@link ThrowingConsumer}s.
* <p>
* This is the same assertion as {@link #satisfies(Consumer[])} except that a {@link ThrowingConsumer} rethrows checked exceptions as {@link RuntimeException}.
* More precisely, {@link RuntimeException} and {@link AssertionError} are rethrown as they are and {@link Throwable} wrapped in a {@link RuntimeException}.
* If each assertion is passed as a separate argument, all of them will be evaluated and assertion error will contain all failures.
* <p>
* Example:
* <pre><code class='java'> // read() throws IOException
* ThrowingConsumer<Reader> hasReachedEOF = reader -> assertThat(reader.read()).isEqualTo(-1);
* ThrowingConsumer<Reader> nextCharacterA = reader -> assertThat(reader.read()).isEqualTo('a');
* ThrowingConsumer<Reader> nextCharacterB = reader -> assertThat(reader.read()).isEqualTo('b');
* ThrowingConsumer<Reader> nextCharacterZ = reader -> assertThat(reader.read()).isEqualTo('z');
*
* // alphabet.txt contains: abcdefghijklmnopqrstuvwxyz
* // empty.txt is empty
*
* // assertion succeeds:
* assertThat(new FileReader("empty.txt")).satisfies(hasReachedEOF);
* assertThat(new FileReader("alphabet.txt")).satisfies(nextCharacterA, nextCharacterB);
*
* // assertion fails:
* assertThat(new FileReader("alphabet.txt")).satisfies(nextCharacterA, hasReachedEOF);
* assertThat(new FileReader("alphabet.txt")).satisfies(nextCharacterB, nextCharacterZ);</code></pre>
*
* @param assertions the group of assertions to run against the object under test - must not be null.
* @return this assertion object.
*
* @throws IllegalArgumentException if any given assertions group is null
* @throws RuntimeException rethrown as is by the given {@link ThrowingConsumer} or wrapping any {@link Throwable}.
* @throws AssertionError rethrown as is by the given {@link ThrowingConsumer}
* @since 3.21.0
*/
@SafeVarargs
public final SELF satisfies(ThrowingConsumer<? super ACTUAL>... assertions) {
return satisfiesForProxy(assertions);
}
// This method is protected in order to be proxied for SoftAssertions / Assumptions.
// The public method for it (the one not ending with "ForProxy") is marked as final and annotated with @SafeVarargs
// in order to avoid compiler warning in user code
protected SELF satisfiesForProxy(Consumer<? super ACTUAL>[] assertionsGroups) throws AssertionError {
checkArgument(stream(assertionsGroups).allMatch(java.util.Objects::nonNull), "No assertions group should be null");
List<AssertionError> assertionErrors = stream(assertionsGroups).map(this::catchOptionalAssertionError)
.filter(Optional::isPresent)
.map(Optional::get)
.collect(toList());
if (!assertionErrors.isEmpty()) {
throw multipleAssertionsError(assertionErrors);
}
return myself;
}
private Optional<AssertionError> catchOptionalAssertionError(Consumer<? super ACTUAL> assertions) {
try {
assertions.accept(actual);
return Optional.empty();
} catch (AssertionError assertionError) {
return Optional.of(assertionError);
}
}
/**
* Verifies that the actual object under test satisfies at least one of the given assertions group expressed as {@link Consumer}s.
* <p>
* This allows users to perform <b>OR like assertions</b> since only one the assertions group has to be met.
* <p>
* {@link #overridingErrorMessage(String, Object...) Overriding error message} is not supported as it would prevent from
* getting the error messages of the failing assertions, these are valuable to figure out what went wrong.<br>
* Describing the assertion is supported (for example with {@link #as(String, Object...)}).
* <p>
* Example:
* <pre><code class='java'> TolkienCharacter frodo = new TolkienCharacter("Frodo", HOBBIT);
*
* Consumer<TolkienCharacter> isHobbit = tolkienCharacter -> assertThat(tolkienCharacter.getRace()).isEqualTo(HOBBIT);
* Consumer<TolkienCharacter> isElf = tolkienCharacter -> assertThat(tolkienCharacter.getRace()).isEqualTo(ELF);
* Consumer<TolkienCharacter> isDwarf = tolkienCharacter -> assertThat(tolkienCharacter.getRace()).isEqualTo(DWARF);
*
* // assertion succeeds:
* assertThat(frodo).satisfiesAnyOf(isElf, isHobbit, isDwarf);
*
* // assertion fails:
* TolkienCharacter boromir = new TolkienCharacter("Boromir", MAN);
* assertThat(boromir).satisfiesAnyOf(isHobbit, isElf, isDwarf);</code></pre>
*
* @param assertions the group of assertions to run against the object under test - must not be null.
* @return this assertion object.
*
* @throws IllegalArgumentException if any given assertions group is null
* @since 3.12.0
*/
@SafeVarargs
public final SELF satisfiesAnyOf(Consumer<? super ACTUAL>... assertions) {
return satisfiesAnyOfForProxy(assertions);
}
/**
* Verifies that the actual object under test satisfies at least one of the given assertions group expressed as {@link ThrowingConsumer}s.
* <p>
* This allows users to perform <b>OR like assertions</b> since only one the assertions group has to be met.
* <p>
* This is the same assertion as {@link #satisfiesAnyOf(Consumer...)} but the given consumers can throw checked exceptions.<br>
* More precisely, {@link RuntimeException} and {@link AssertionError} are rethrown as they are and {@link Throwable} wrapped in a {@link RuntimeException}.
* <p>
* {@link #overridingErrorMessage(String, Object...) Overriding error message} is not supported as it would prevent from
* getting the error messages of the failing assertions, these are valuable to figure out what went wrong.<br>
* Describing the assertion is supported (for example with {@link #as(String, Object...)}).
* <p>
* Example:
* <pre><code class='java'> // read() throws IOException
* ThrowingConsumer<Reader> hasReachedEOF = reader -> assertThat(reader.read()).isEqualTo(-1);
* ThrowingConsumer<Reader> startsWithZ = reader -> assertThat(reader.read()).isEqualTo('Z');
*
* // assertion succeeds as the file is empty (note that if hasReachedEOF was declared as a Consumer<Reader> the following line would not compile):
* assertThat(new FileReader("empty.txt")).satisfiesAnyOf(hasReachedEOF, startsWithZ);
*
* // alphabet.txt contains: abcdefghijklmnopqrstuvwxyz
* // assertion fails as alphabet.txt is not empty and starts with 'a':
* assertThat(new FileReader("alphabet.txt")).satisfiesAnyOf(hasReachedEOF, startsWithZ);</code></pre>
*
* @param assertions the group of assertions to run against the object under test - must not be null.
* @return this assertion object.
*
* @throws IllegalArgumentException if any given assertions group is null
* @throws RuntimeException rethrown as is by the given {@link ThrowingConsumer} or wrapping any {@link Throwable}.
* @throws AssertionError rethrown as is by the given {@link ThrowingConsumer}
* @since 3.21.0
*/
@SafeVarargs
public final SELF satisfiesAnyOf(ThrowingConsumer<? super ACTUAL>... assertions) {
return satisfiesAnyOfForProxy(assertions);
}
// This method is protected in order to be proxied for SoftAssertions / Assumptions.
// The public method for it (the one not ending with "ForProxy") is marked as final and annotated with @SafeVarargs
// in order to avoid compiler warning in user code
protected SELF satisfiesAnyOfForProxy(Consumer<? super ACTUAL>[] assertionsGroups) throws AssertionError {
checkArgument(stream(assertionsGroups).allMatch(java.util.Objects::nonNull), "No assertions group should be null");
// use a for loop over stream to return as soon as one assertion is met
List<AssertionError> assertionErrors = list();
for (Consumer<? super ACTUAL> assertionsGroup : assertionsGroups) {
Optional<AssertionError> maybeError = catchOptionalAssertionError(assertionsGroup);
if (!maybeError.isPresent()) {
return myself;
}
assertionErrors.add(maybeError.get());
}
throw multipleAssertionsError(assertionErrors);