How to use singleElement method of org.assertj.core.api.AbstractObjectArrayAssert class

Best Assertj code snippet using org.assertj.core.api.AbstractObjectArrayAssert.singleElement

Source:AssertJAssertions.java Github

copy

Full Screen

...1201 public AbstractAssert last() { return (AbstractAssert) (Object) null; }1202 public AbstractAssert last(InstanceOfAssertFactory p0) { return (AbstractAssert) (Object) null; }1203 public AbstractAssert element(int p0) { return (AbstractAssert) (Object) null; }1204 public AbstractAssert element(int p0, InstanceOfAssertFactory p1) { return (AbstractAssert) (Object) null; }1205 public AbstractAssert singleElement() { return (AbstractAssert) (Object) null; }1206 public AbstractAssert singleElement(InstanceOfAssertFactory p0) { return (AbstractAssert) (Object) null; }1207 public AbstractIterableAssert filteredOn(java.util.function.Predicate p0) { return (AbstractIterableAssert) (Object) null; }1208 public AbstractIterableAssert allMatch(java.util.function.Predicate p0) { return (AbstractIterableAssert) (Object) null; }1209 public AbstractIterableAssert allMatch(java.util.function.Predicate p0, String p1) { return (AbstractIterableAssert) (Object) null; }1210 public AbstractIterableAssert allSatisfy(java.util.function.Consumer p0) { return (AbstractIterableAssert) (Object) null; }1211 public AbstractIterableAssert anyMatch(java.util.function.Predicate p0) { return (AbstractIterableAssert) (Object) null; }1212 public AbstractIterableAssert zipSatisfy(Iterable p0, java.util.function.BiConsumer p1) { return (AbstractIterableAssert) (Object) null; }1213 public AbstractIterableAssert anySatisfy(java.util.function.Consumer p0) { return (AbstractIterableAssert) (Object) null; }1214 public AbstractIterableAssert noneSatisfy(java.util.function.Consumer p0) { return (AbstractIterableAssert) (Object) null; }1215 public AbstractIterableAssert satisfiesExactly(java.util.function.Consumer[] p0) { return (AbstractIterableAssert) (Object) null; }1216 public AbstractIterableAssert satisfiesExactlyInAnyOrder(java.util.function.Consumer[] p0) { return (AbstractIterableAssert) (Object) null; }1217 public AbstractIterableAssert as(String p0, Object[] p1) { return (AbstractIterableAssert) (Object) null; }1218 public AbstractIterableAssert as(org.assertj.core.description.Description p0) { return (AbstractIterableAssert) (Object) null; }1219 public AbstractIterableAssert describedAs(org.assertj.core.description.Description p0) { return (AbstractIterableAssert) (Object) null; }1220 public AbstractIterableAssert describedAs(String p0, Object[] p1) { return (AbstractIterableAssert) (Object) null; }...

Full Screen

Full Screen

Source:AbstractObjectArrayAssert.java Github

copy

Full Screen

...3789 }3790 /**3791 * Verifies that the array under test contains a single element and allows to perform assertions on that element.3792 * <p>3793 * By default available assertions after {@code singleElement()} are {@code Object} assertions, it is possible though to3794 * get more specific assertions by using {@link #singleElement(InstanceOfAssertFactory) singleElement(element assert factory)}3795 * <p>3796 * Example:3797 * <pre><code class='java'> String[] babySimpsons = { "Maggie" };3798 *3799 * // assertion succeeds, only Object assertions are available after singleElement()3800 * assertThat(babySimpsons).singleElement()3801 * .isEqualTo("Maggie");3802 *3803 * // assertion fails3804 * assertThat(babySimpsons).singleElement()3805 * .isEqualTo("Homer");3806 *3807 * // assertion fails because list contains no elements3808 * assertThat(emptyList()).singleElement();3809 *3810 *3811 * // assertion fails because list contains more than one element3812 * String[] simpsons = { "Homer", "Marge", "Lisa", "Bart", "Maggie" };3813 * assertThat(simpsons).singleElement();</code></pre>3814 *3815 * @return the assertion on the first element3816 * @throws AssertionError if the actual array does not contain exactly one element.3817 * @since 3.22.03818 * @see #singleElement(InstanceOfAssertFactory)3819 */3820 @CheckReturnValue3821 public ObjectAssert<ELEMENT> singleElement() {3822 return internalSingleElement();3823 }3824 /**3825 * Verifies that the array under test contains a single element and allows to perform assertions on that element, 3826 * the assertions are strongly typed according to the given {@link AssertFactory} parameter.3827 * <p>3828 * Example: use of {@code String} assertions after {@code singleElement(as(STRING))}3829 * <pre><code class='java'> import static org.assertj.core.api.InstanceOfAssertFactories.STRING;3830 * import static org.assertj.core.api.InstanceOfAssertFactories.INTEGER;3831 * import static org.assertj.core.api.Assertions.as; // syntactic sugar3832 *3833 * String[] babySimpsons = { "Maggie" };3834 *3835 * // assertion succeeds3836 * assertThat(babySimpsons).singleElement(as(STRING))3837 * .startsWith("Mag");3838 *3839 * // assertion fails3840 * assertThat(babySimpsons).singleElement(as(STRING))3841 * .startsWith("Lis");3842 *3843 * // assertion fails because of wrong factory type3844 * assertThat(babySimpsons).singleElement(as(INTEGER))3845 * .isZero();3846 *3847 * // assertion fails because list contains no elements3848 * assertThat(emptyList()).singleElement(as(STRING));3849 *3850 * // assertion fails because list contains more than one element3851 * String[] simpsons = { "Homer", "Marge", "Lisa", "Bart", "Maggie" };3852 * assertThat(simpsons).singleElement(as(STRING));</code></pre>3853 *3854 * @param <ASSERT> the type of the resulting {@code Assert}3855 * @param assertFactory the factory which verifies the type and creates the new {@code Assert}3856 * @return a new narrowed {@link Assert} instance for assertions chaining on the single element3857 * @throws AssertionError if the actual array does not contain exactly one element.3858 * @throws NullPointerException if the given factory is {@code null}.3859 * @since 3.22.03860 */3861 @CheckReturnValue3862 public <ASSERT extends AbstractAssert<?, ?>> ASSERT singleElement(InstanceOfAssertFactory<?, ASSERT> assertFactory) {3863 return internalSingleElement().asInstanceOf(assertFactory);3864 }3865 private ObjectAssert<ELEMENT> internalSingleElement() {3866 arrays.assertHasSize(info, actual, 1);3867 return toAssert(actual[0], navigationDescription("check single element"));3868 }3869 protected String navigationDescription(String propertyName) {3870 String text = descriptionText();3871 if (Strings.isNullOrEmpty(text)) {3872 text = removeAssert(this.getClass().getSimpleName());3873 }3874 return text + " " + propertyName;3875 }3876 private static String removeAssert(String text) {...

Full Screen

Full Screen

Source:AbstractIterableAssert.java Github

copy

Full Screen

...294 * @throws AssertionError if the {@link Iterable} does not have a unique element.295 * @throws AssertionError if the {@link Iterable}'s unique element does not satisfy the given assertions.296 *297 * @since 3.5.0298 * @deprecated use {@link #singleElement()} instead299 */300 @Deprecated301 @Override302 public SELF hasOnlyOneElementSatisfying(Consumer<? super ELEMENT> elementAssertions) {303 iterables.assertHasSize(info, actual, 1);304 elementAssertions.accept(actual.iterator().next());305 return myself;306 }307 /**308 * {@inheritDoc}309 */310 @Override311 public SELF hasSameSizeAs(Object other) {312 iterables.assertHasSameSizeAs(info, actual, other);313 return myself;314 }315 /**316 * {@inheritDoc}317 */318 @Override319 public SELF hasSameSizeAs(Iterable<?> other) {320 iterables.assertHasSameSizeAs(info, actual, other);321 return myself;322 }323 /**324 * {@inheritDoc}325 */326 @Override327 public SELF contains(@SuppressWarnings("unchecked") ELEMENT... values) {328 iterables.assertContains(info, actual, values);329 return myself;330 }331 /**332 * {@inheritDoc}333 */334 @Override335 public SELF containsOnly(@SuppressWarnings("unchecked") ELEMENT... values) {336 iterables.assertContainsOnly(info, actual, values);337 return myself;338 }339 /**340 * {@inheritDoc}341 */342 @Override343 public SELF containsOnlyOnce(@SuppressWarnings("unchecked") ELEMENT... values) {344 iterables.assertContainsOnlyOnce(info, actual, values);345 return myself;346 }347 /**348 * {@inheritDoc}349 */350 @Override351 public SELF containsOnlyNulls() {352 iterables.assertContainsOnlyNulls(info, actual);353 return myself;354 }355 /**356 * {@inheritDoc}357 */358 @Override359 public SELF containsExactly(@SuppressWarnings("unchecked") ELEMENT... values) {360 iterables.assertContainsExactly(info, actual, values);361 return myself;362 }363 /** {@inheritDoc} */364 @Override365 public SELF containsExactlyInAnyOrder(@SuppressWarnings("unchecked") ELEMENT... values) {366 iterables.assertContainsExactlyInAnyOrder(info, actual, values);367 return myself;368 }369 /**370 * {@inheritDoc}371 */372 @Override373 public SELF containsExactlyInAnyOrderElementsOf(Iterable<? extends ELEMENT> values) {374 return containsExactlyInAnyOrder(toArray(values));375 }376 /**377 * {@inheritDoc}378 */379 @Override380 public SELF isSubsetOf(Iterable<? extends ELEMENT> values) {381 iterables.assertIsSubsetOf(info, actual, values);382 return myself;383 }384 /**385 * {@inheritDoc}386 */387 @Override388 public SELF isSubsetOf(@SuppressWarnings("unchecked") ELEMENT... values) {389 iterables.assertIsSubsetOf(info, actual, Arrays.asList(values));390 return myself;391 }392 /**393 * {@inheritDoc}394 */395 @Override396 public SELF containsSequence(@SuppressWarnings("unchecked") ELEMENT... sequence) {397 iterables.assertContainsSequence(info, actual, sequence);398 return myself;399 }400 /**401 * {@inheritDoc}402 */403 @Override404 public SELF containsSequence(Iterable<? extends ELEMENT> sequence) {405 checkSequenceIsNotNull(sequence);406 iterables.assertContainsSequence(info, actual, toArray(sequence));407 return myself;408 }409 /**410 * {@inheritDoc}411 */412 @Override413 public SELF doesNotContainSequence(@SuppressWarnings("unchecked") ELEMENT... sequence) {414 iterables.assertDoesNotContainSequence(info, actual, sequence);415 return myself;416 }417 /**418 * {@inheritDoc}419 */420 @Override421 public SELF doesNotContainSequence(Iterable<? extends ELEMENT> sequence) {422 checkSequenceIsNotNull(sequence);423 iterables.assertDoesNotContainSequence(info, actual, toArray(sequence));424 return myself;425 }426 /**427 * {@inheritDoc}428 */429 @Override430 public SELF containsSubsequence(@SuppressWarnings("unchecked") ELEMENT... subsequence) {431 iterables.assertContainsSubsequence(info, actual, subsequence);432 return myself;433 }434 /**435 * {@inheritDoc}436 */437 @Override438 public SELF containsSubsequence(Iterable<? extends ELEMENT> subsequence) {439 checkSubsequenceIsNotNull(subsequence);440 iterables.assertContainsSubsequence(info, actual, toArray(subsequence));441 return myself;442 }443 /**444 * {@inheritDoc}445 */446 @Override447 public SELF doesNotContainSubsequence(@SuppressWarnings("unchecked") ELEMENT... subsequence) {448 iterables.assertDoesNotContainSubsequence(info, actual, subsequence);449 return myself;450 }451 /**452 * {@inheritDoc}453 */454 @Override455 public SELF doesNotContainSubsequence(Iterable<? extends ELEMENT> subsequence) {456 checkSubsequenceIsNotNull(subsequence);457 iterables.assertDoesNotContainSubsequence(info, actual, toArray(subsequence));458 return myself;459 }460 @Override461 public SELF doesNotContain(@SuppressWarnings("unchecked") ELEMENT... values) {462 iterables.assertDoesNotContain(info, actual, values);463 return myself;464 }465 @Override466 public SELF doesNotContainAnyElementsOf(Iterable<? extends ELEMENT> iterable) {467 iterables.assertDoesNotContainAnyElementsOf(info, actual, iterable);468 return myself;469 }470 /**471 * {@inheritDoc}472 */473 @Override474 public SELF doesNotHaveDuplicates() {475 iterables.assertDoesNotHaveDuplicates(info, actual);476 return myself;477 }478 /**479 * {@inheritDoc}480 */481 @Override482 public SELF startsWith(@SuppressWarnings("unchecked") ELEMENT... sequence) {483 iterables.assertStartsWith(info, actual, sequence);484 return myself;485 }486 /**487 * {@inheritDoc}488 */489 @Override490 public SELF endsWith(ELEMENT first, @SuppressWarnings("unchecked") ELEMENT... rest) {491 iterables.assertEndsWith(info, actual, first, rest);492 return myself;493 }494 /**495 * {@inheritDoc}496 */497 @Override498 public SELF endsWith(ELEMENT[] sequence) {499 iterables.assertEndsWith(info, actual, sequence);500 return myself;501 }502 /**503 * {@inheritDoc}504 */505 @Override506 public SELF containsNull() {507 iterables.assertContainsNull(info, actual);508 return myself;509 }510 /**511 * {@inheritDoc}512 */513 @Override514 public SELF doesNotContainNull() {515 iterables.assertDoesNotContainNull(info, actual);516 return myself;517 }518 /**519 * {@inheritDoc}520 */521 @Override522 public SELF are(Condition<? super ELEMENT> condition) {523 iterables.assertAre(info, actual, condition);524 return myself;525 }526 /**527 * {@inheritDoc}528 */529 @Override530 public SELF areNot(Condition<? super ELEMENT> condition) {531 iterables.assertAreNot(info, actual, condition);532 return myself;533 }534 /**535 * {@inheritDoc}536 */537 @Override538 public SELF have(Condition<? super ELEMENT> condition) {539 iterables.assertHave(info, actual, condition);540 return myself;541 }542 /**543 * {@inheritDoc}544 */545 @Override546 public SELF doNotHave(Condition<? super ELEMENT> condition) {547 iterables.assertDoNotHave(info, actual, condition);548 return myself;549 }550 /**551 * {@inheritDoc}552 */553 @Override554 public SELF areAtLeastOne(Condition<? super ELEMENT> condition) {555 areAtLeast(1, condition);556 return myself;557 }558 /**559 * {@inheritDoc}560 */561 @Override562 public SELF areAtLeast(int times, Condition<? super ELEMENT> condition) {563 iterables.assertAreAtLeast(info, actual, times, condition);564 return myself;565 }566 /**567 * {@inheritDoc}568 */569 @Override570 public SELF areAtMost(int times, Condition<? super ELEMENT> condition) {571 iterables.assertAreAtMost(info, actual, times, condition);572 return myself;573 }574 /**575 * {@inheritDoc}576 */577 @Override578 public SELF areExactly(int times, Condition<? super ELEMENT> condition) {579 iterables.assertAreExactly(info, actual, times, condition);580 return myself;581 }582 /** {@inheritDoc} */583 @Override584 public SELF haveAtLeastOne(Condition<? super ELEMENT> condition) {585 return haveAtLeast(1, condition);586 }587 /**588 * {@inheritDoc}589 */590 @Override591 public SELF haveAtLeast(int times, Condition<? super ELEMENT> condition) {592 iterables.assertHaveAtLeast(info, actual, times, condition);593 return myself;594 }595 /**596 * {@inheritDoc}597 */598 @Override599 public SELF haveAtMost(int times, Condition<? super ELEMENT> condition) {600 iterables.assertHaveAtMost(info, actual, times, condition);601 return myself;602 }603 /**604 * {@inheritDoc}605 */606 @Override607 public SELF haveExactly(int times, Condition<? super ELEMENT> condition) {608 iterables.assertHaveExactly(info, actual, times, condition);609 return myself;610 }611 /**612 * Verifies that at least one element in the actual {@code Iterable} has the specified type (matching includes613 * subclasses of the given type).614 * <p>615 * Example:616 * <pre><code class='java'> List&lt;Number&gt; numbers = new ArrayList&lt;Number&gt;();617 * numbers.add(1);618 * numbers.add(2L);619 *620 * // successful assertion:621 * assertThat(numbers).hasAtLeastOneElementOfType(Long.class);622 *623 * // assertion failure:624 * assertThat(numbers).hasAtLeastOneElementOfType(Float.class);</code></pre>625 *626 * @param expectedType the expected type.627 * @return this assertion object.628 * @throws NullPointerException if the given type is {@code null}.629 * @throws AssertionError if the actual {@code Object} group does not have any elements of the given type.630 */631 @Override632 public SELF hasAtLeastOneElementOfType(Class<?> expectedType) {633 // reuse code from object arrays as the logic is the same634 // (ok since this assertion doesn't rely on a comparison strategy)635 ObjectArrays.instance().assertHasAtLeastOneElementOfType(info, toArray(actual), expectedType);636 return myself;637 }638 /**639 * Verifies that all elements in the actual {@code Iterable} have the specified type (matching includes640 * subclasses of the given type).641 * <p>642 * Example:643 * <pre><code class='java'> List&lt;Number&gt; numbers = new ArrayList&lt;Number&gt;();644 * numbers.add(1);645 * numbers.add(2);646 * numbers.add(3);647 *648 * // successful assertions:649 * assertThat(numbers).hasOnlyElementsOfType(Number.class);650 * assertThat(numbers).hasOnlyElementsOfType(Integer.class);651 *652 * // assertion failure:653 * assertThat(numbers).hasOnlyElementsOfType(Long.class);</code></pre>654 *655 * @param expectedType the expected type.656 * @return this assertion object.657 * @throws NullPointerException if the given type is {@code null}.658 * @throws AssertionError if one element is not of the expected type.659 */660 @Override661 public SELF hasOnlyElementsOfType(Class<?> expectedType) {662 // reuse code from object arrays as the logic is the same663 // (ok since this assertion doesn't rely on a comparison strategy)664 ObjectArrays.instance().assertHasOnlyElementsOfType(info, toArray(actual), expectedType);665 return myself;666 }667 /**668 * Verifies that all elements in the actual {@code Iterable} do not have the specified types (including subclasses).669 * <p>670 * Example:671 * <pre><code class='java'> List&lt;Number&gt; numbers = new ArrayList&lt;&gt;();672 * numbers.add(1);673 * numbers.add(2);674 * numbers.add(3.0);675 *676 * // successful assertions:677 * assertThat(numbers).doesNotHaveAnyElementsOfTypes(Long.class, Float.class);678 *679 * // assertion failure:680 * assertThat(numbers).doesNotHaveAnyElementsOfTypes(Long.class, Integer.class);</code></pre>681 *682 * @param unexpectedTypes the not expected types.683 * @return this assertion object.684 * @throws NullPointerException if the given type is {@code null}.685 * @throws AssertionError if one element's type matches the given types.686 * @since 2.9.0 / 3.9.0687 */688 @Override689 public SELF doesNotHaveAnyElementsOfTypes(Class<?>... unexpectedTypes) {690 ObjectArrays.instance().assertDoesNotHaveAnyElementsOfTypes(info, toArray(actual), unexpectedTypes);691 return myself;692 }693 /** {@inheritDoc} */694 @Override695 public SELF hasOnlyElementsOfTypes(Class<?>... types) {696 ObjectArrays.instance().assertHasOnlyElementsOfTypes(info, toArray(actual), types);697 return myself;698 }699 /**700 * {@inheritDoc}701 */702 @Override703 public SELF containsAll(Iterable<? extends ELEMENT> iterable) {704 iterables.assertContainsAll(info, actual, iterable);705 return myself;706 }707 /**708 * {@inheritDoc}709 */710 @Override711 @CheckReturnValue712 public SELF usingElementComparator(Comparator<? super ELEMENT> elementComparator) {713 this.iterables = new Iterables(new ComparatorBasedComparisonStrategy(elementComparator));714 // to have the same semantics on base assertions like isEqualTo, we need to use an iterable comparator comparing715 // elements with elementComparator parameter716 objects = new Objects(new IterableElementComparisonStrategy<>(elementComparator));717 return myself;718 }719 @CheckReturnValue720 private SELF usingExtendedByTypesElementComparator(Comparator<Object> elementComparator) {721 return usingElementComparator(new ExtendedByTypesComparator(elementComparator, getComparatorsByType()));722 }723 /**724 * {@inheritDoc}725 */726 @Override727 @CheckReturnValue728 public SELF usingDefaultElementComparator() {729 this.iterables = Iterables.instance();730 return usingDefaultComparator();731 }732 /**733 * Verifies that the actual {@link Iterable} contains at least one of the given values.734 * <p>735 * Example :736 * <pre><code class='java'> Iterable&lt;String&gt; abc = Arrays.asList("a", "b", "c");737 *738 * // assertions will pass739 * assertThat(abc).containsAnyOf("b")740 * .containsAnyOf("b", "c")741 * .containsAnyOf("a", "b", "c")742 * .containsAnyOf("a", "b", "c", "d")743 * .containsAnyOf("e", "f", "g", "b");744 *745 * // assertions will fail746 * assertThat(abc).containsAnyOf("d");747 * assertThat(abc).containsAnyOf("d", "e", "f", "g");</code></pre>748 *749 * @param values the values whose at least one which is expected to be in the {@code Iterable} under test.750 * @return {@code this} assertion object.751 * @throws NullPointerException if the array of values is {@code null}.752 * @throws IllegalArgumentException if the array of values is empty and the {@code Iterable} under test is not empty.753 * @throws AssertionError if the {@code Iterable} under test is {@code null}.754 * @throws AssertionError if the {@code Iterable} under test does not contain any of the given {@code values}.755 * @since 2.9.0 / 3.9.0756 */757 @Override758 public SELF containsAnyOf(@SuppressWarnings("unchecked") ELEMENT... values) {759 iterables.assertContainsAnyOf(info, actual, values);760 return myself;761 }762 /**763 * Verifies that the {@link Iterable} under test contains at least one of the given {@link Iterable} elements.764 * <p>765 * Example :766 * <pre><code class='java'> Iterable&lt;String&gt; abc = Arrays.asList("a", "b", "c");767 *768 * // assertions will pass769 * assertThat(abc).containsAnyElementsOf(Arrays.asList("b"))770 * .containsAnyElementsOf(Arrays.asList("b", "c"))771 * .containsAnyElementsOf(Arrays.asList("a", "b", "c"))772 * .containsAnyElementsOf(Arrays.asList("a", "b", "c", "d"))773 * .containsAnyElementsOf(Arrays.asList("e", "f", "g", "b"));774 *775 * // assertions will fail776 * assertThat(abc).containsAnyElementsOf(Arrays.asList("d"));777 * assertThat(abc).containsAnyElementsOf(Arrays.asList("d", "e", "f", "g"));</code></pre>778 *779 * @param iterable the iterable whose at least one element is expected to be in the {@code Iterable} under test.780 * @return {@code this} assertion object.781 * @throws NullPointerException if the iterable of expected values is {@code null}.782 * @throws IllegalArgumentException if the iterable of expected values is empty and the {@code Iterable} under test is not empty.783 * @throws AssertionError if the {@code Iterable} under test is {@code null}.784 * @throws AssertionError if the {@code Iterable} under test does not contain any of elements from the given {@code Iterable}.785 * @since 2.9.0 / 3.9.0786 */787 @Override788 public SELF containsAnyElementsOf(Iterable<? extends ELEMENT> iterable) {789 return containsAnyOf(toArray(iterable));790 }791 /**792 * Extract the values of the given field or property from the Iterable's elements under test into a new Iterable, this new793 * Iterable becoming the Iterable under test.794 * <p>795 * It allows you to test a property/field of the Iterable's elements instead of testing the elements themselves, which796 * can be be much less work !797 * <p>798 * Let's take a look at an example to make things clearer :799 * <pre><code class='java'> // build a list of TolkienCharacters: a TolkienCharacter has a name, and age and a Race (a specific class)800 * // they can be public field or properties, both can be extracted.801 * List&lt;TolkienCharacter&gt; fellowshipOfTheRing = new ArrayList&lt;TolkienCharacter&gt;();802 *803 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Frodo&quot;, 33, HOBBIT));804 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Sam&quot;, 38, HOBBIT));805 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Gandalf&quot;, 2020, MAIA));806 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Legolas&quot;, 1000, ELF));807 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Pippin&quot;, 28, HOBBIT));808 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Gimli&quot;, 139, DWARF));809 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Aragorn&quot;, 87, MAN);810 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Boromir&quot;, 37, MAN));811 *812 * // let's verify the names of the TolkienCharacters in fellowshipOfTheRing :813 *814 * assertThat(fellowshipOfTheRing).extracting(&quot;name&quot;)815 * .contains(&quot;Boromir&quot;, &quot;Gandalf&quot;, &quot;Frodo&quot;)816 * .doesNotContain(&quot;Sauron&quot;, &quot;Elrond&quot;);817 *818 * // you can extract nested properties/fields like the name of the race :819 *820 * assertThat(fellowshipOfTheRing).extracting(&quot;race.name&quot;)821 * .contains(&quot;Hobbit&quot;, &quot;Elf&quot;)822 * .doesNotContain(&quot;Orc&quot;);</code></pre>823 * <p>824 * A property with the given name is searched for first. If it doesn't exist a field with the given name is looked825 * for. If the field does not exist an {@link IntrospectionError} is thrown. By default private fields are read but826 * you can change this with {@link Assertions#setAllowComparingPrivateFields(boolean)}. Trying to read a private field827 * when it's not allowed leads to an {@link IntrospectionError}.828 * <p>829 * Note that the order of extracted property/field values is consistent with the iteration order of the Iterable under830 * test, for example if it's a {@link HashSet}, you won't be able to make any assumptions on the extracted values831 * order.832 * <hr>833 * <p>834 * Extracting also support maps, that is, instead of extracting values from an Object, it extracts maps values835 * corresponding to the given keys.836 * <p>837 * Example:838 * <pre><code class='java'> Employee yoda = new Employee(1L, new Name("Yoda"), 800);839 * Employee luke = new Employee(2L, new Name("Luke"), 22);840 * Employee han = new Employee(3L, new Name("Han"), 31);841 *842 * // build two maps843 * Map&lt;String, Employee&gt; map1 = new HashMap&lt;&gt;();844 * map1.put("key1", yoda);845 * map1.put("key2", luke);846 *847 * Map&lt;String, Employee&gt; map2 = new HashMap&lt;&gt;();848 * map2.put("key1", yoda);849 * map2.put("key2", han);850 *851 * // instead of a list of objects, we have a list of maps852 * List&lt;Map&lt;String, Employee&gt;&gt; maps = asList(map1, map2);853 *854 * // extracting a property in that case = get values from maps using the property as a key855 * assertThat(maps).extracting("key2").containsExactly(luke, han);856 * assertThat(maps).extracting("key1").containsExactly(yoda, yoda);857 *858 * // type safe version859 * assertThat(maps).extracting(key2, Employee.class).containsExactly(luke, han);860 *861 * // it works with several keys, extracted values being wrapped in a Tuple862 * assertThat(maps).extracting("key1", "key2").containsExactly(tuple(yoda, luke), tuple(yoda, han));863 *864 * // unknown keys leads to null (map behavior)865 * assertThat(maps).extracting("bad key").containsExactly(null, null);</code></pre>866 *867 * @param propertyOrField the property/field to extract from the elements of the Iterable under test868 * @return a new assertion object whose object under test is the list of extracted property/field values.869 * @throws IntrospectionError if no field or property exists with the given name in one of the initial870 * Iterable's element.871 */872 @CheckReturnValue873 public AbstractListAssert<?, List<? extends Object>, Object, ObjectAssert<Object>> extracting(String propertyOrField) {874 List<Object> values = FieldsOrPropertiesExtractor.extract(actual, byName(propertyOrField));875 String extractedDescription = extractedDescriptionOf(propertyOrField);876 String description = mostRelevantDescription(info.description(), extractedDescription);877 return newListAssertInstanceForMethodsChangingElementType(values).as(description);878 }879 /**880 * Extract the result of given method invocation on the Iterable's elements under test into a new Iterable, this new881 * Iterable becoming the Iterable under test.882 * <p>883 * It allows you to test the method results of the Iterable's elements instead of testing the elements themselves. This884 * is especially useful for classes that do not conform to the Java Bean's getter specification (i.e. public String885 * toString() or public String status() instead of public String getStatus()).886 * <p>887 * Let's take a look at an example to make things clearer :888 * <pre><code class='java'> // Build a array of WesterosHouse, a WesterosHouse has a method: public String sayTheWords()889 *890 * List&lt;WesterosHouse&gt; greatHouses = new ArrayList&lt;WesterosHouse&gt;();891 * greatHouses.add(new WesterosHouse(&quot;Stark&quot;, &quot;Winter is Coming&quot;));892 * greatHouses.add(new WesterosHouse(&quot;Lannister&quot;, &quot;Hear Me Roar!&quot;));893 * greatHouses.add(new WesterosHouse(&quot;Greyjoy&quot;, &quot;We Do Not Sow&quot;));894 * greatHouses.add(new WesterosHouse(&quot;Baratheon&quot;, &quot;Our is the Fury&quot;));895 * greatHouses.add(new WesterosHouse(&quot;Martell&quot;, &quot;Unbowed, Unbent, Unbroken&quot;));896 * greatHouses.add(new WesterosHouse(&quot;Tyrell&quot;, &quot;Growing Strong&quot;));897 *898 * // let's verify the words of the great houses of Westeros:899 * assertThat(greatHouses).extractingResultOf(&quot;sayTheWords&quot;)900 * .contains(&quot;Winter is Coming&quot;, &quot;We Do Not Sow&quot;, &quot;Hear Me Roar&quot;)901 * .doesNotContain(&quot;Lannisters always pay their debts&quot;);</code></pre>902 *903 * Following requirements have to be met to extract method results:904 * <ul>905 * <li>method has to be public,</li>906 * <li>method cannot accept any arguments,</li>907 * <li>method cannot return void.</li>908 * </ul>909 * <p>910 * Note that the order of extracted results is consistent with the iteration order of the Iterable under test, for911 * example if it's a {@link HashSet}, you won't be able to make any assumptions on the extracted results order.912 *913 * @param method the name of the method which result is to be extracted from the array under test914 * @return a new assertion object whose object under test is the Iterable of extracted values.915 * @throws IllegalArgumentException if no method exists with the given name, or method is not public, or method does916 * return void, or method accepts arguments.917 */918 @CheckReturnValue919 public AbstractListAssert<?, List<? extends Object>, Object, ObjectAssert<Object>> extractingResultOf(String method) {920 // can't refactor by calling extractingResultOf(method, Object.class) as SoftAssertion would fail921 List<Object> values = FieldsOrPropertiesExtractor.extract(actual, resultOf(method));922 String extractedDescription = extractedDescriptionOfMethod(method);923 String description = mostRelevantDescription(info.description(), extractedDescription);924 return newListAssertInstanceForMethodsChangingElementType(values).as(description);925 }926 /**927 * Extract the result of given method invocation on the Iterable's elements under test into a new list of the given928 * class, this new List becoming the object under test.929 * <p>930 * It allows you to test the method results of the Iterable's elements instead of testing the elements themselves, it931 * is especially useful for classes that do not conform to the Java Bean's getter specification (i.e. public String932 * toString() or public String status() instead of public String getStatus()).933 * <p>934 * Let's take an example to make things clearer :935 * <pre><code class='java'> // Build a array of WesterosHouse, a WesterosHouse has a method: public String sayTheWords()936 * List&lt;WesterosHouse&gt; greatHouses = new ArrayList&lt;WesterosHouse&gt;();937 * greatHouses.add(new WesterosHouse(&quot;Stark&quot;, &quot;Winter is Coming&quot;));938 * greatHouses.add(new WesterosHouse(&quot;Lannister&quot;, &quot;Hear Me Roar!&quot;));939 * greatHouses.add(new WesterosHouse(&quot;Greyjoy&quot;, &quot;We Do Not Sow&quot;));940 * greatHouses.add(new WesterosHouse(&quot;Baratheon&quot;, &quot;Our is the Fury&quot;));941 * greatHouses.add(new WesterosHouse(&quot;Martell&quot;, &quot;Unbowed, Unbent, Unbroken&quot;));942 * greatHouses.add(new WesterosHouse(&quot;Tyrell&quot;, &quot;Growing Strong&quot;));943 *944 * // let's verify the words of the great houses of Westeros:945 * assertThat(greatHouses).extractingResultOf(&quot;sayTheWords&quot;, String.class)946 * .contains(&quot;Winter is Coming&quot;, &quot;We Do Not Sow&quot;, &quot;Hear Me Roar&quot;)947 * .doesNotContain(&quot;Lannisters always pay their debts&quot;);</code></pre>948 *949 * Following requirements have to be met to extract method results:950 * <ul>951 * <li>method has to be public,</li>952 * <li>method cannot accept any arguments,</li>953 * <li>method cannot return void.</li>954 * </ul>955 * <p>956 * Note that the order of extracted property/field values is consistent with the iteration order of the Iterable under957 * test, for example if it's a {@link HashSet}, you won't be able to make any assumptions of the extracted values958 * order.959 *960 * @param <P> the type of elements extracted.961 * @param method the name of the method which result is to be extracted from the array under test962 * @param extractedType type of element of the extracted List963 * @return a new assertion object whose object under test is the Iterable of extracted values.964 * @throws IllegalArgumentException if no method exists with the given name, or method is not public, or method does965 * return void or method accepts arguments.966 */967 @CheckReturnValue968 public <P> AbstractListAssert<?, List<? extends P>, P, ObjectAssert<P>> extractingResultOf(String method,969 Class<P> extractedType) {970 @SuppressWarnings("unchecked")971 List<P> values = (List<P>) FieldsOrPropertiesExtractor.extract(actual, resultOf(method));972 String extractedDescription = extractedDescriptionOfMethod(method);973 String description = mostRelevantDescription(info.description(), extractedDescription);974 return newListAssertInstanceForMethodsChangingElementType(values).as(description);975 }976 /**977 * Extract the values of given field or property from the Iterable's elements under test into a new Iterable, this new978 * Iterable becoming the Iterable under test.979 * <p>980 * It allows you to test a property/field of the Iterable's elements instead of testing the elements themselves,981 * which can be much less work !982 * <p>983 * Let's take an example to make things clearer :984 * <pre><code class='java'> // Build a list of TolkienCharacter, a TolkienCharacter has a name, and age and a Race (a specific class)985 * // they can be public field or properties, both can be extracted.986 * List&lt;TolkienCharacter&gt; fellowshipOfTheRing = new ArrayList&lt;TolkienCharacter&gt;();987 *988 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Frodo&quot;, 33, HOBBIT));989 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Sam&quot;, 38, HOBBIT));990 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Gandalf&quot;, 2020, MAIA));991 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Legolas&quot;, 1000, ELF));992 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Pippin&quot;, 28, HOBBIT));993 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Gimli&quot;, 139, DWARF));994 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Aragorn&quot;, 87, MAN);995 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Boromir&quot;, 37, MAN));996 *997 * // let's verify the names of TolkienCharacter in fellowshipOfTheRing :998 * assertThat(fellowshipOfTheRing).extracting(&quot;name&quot;, String.class)999 * .contains(&quot;Boromir&quot;, &quot;Gandalf&quot;, &quot;Frodo&quot;)1000 * .doesNotContain(&quot;Sauron&quot;, &quot;Elrond&quot;);1001 *1002 * // you can extract nested property/field like the name of Race :1003 * assertThat(fellowshipOfTheRing).extracting(&quot;race.name&quot;, String.class)1004 * .contains(&quot;Hobbit&quot;, &quot;Elf&quot;)1005 * .doesNotContain(&quot;Orc&quot;);</code></pre>1006 *1007 * A property with the given name is looked for first, if it doesn't exist then a field with the given name is looked1008 * for, if the field does not exist an {@link IntrospectionError} is thrown, by default private fields are read but1009 * you can change this with {@link Assertions#setAllowComparingPrivateFields(boolean)}, trying to read a private field1010 * when it's not allowed leads to an {@link IntrospectionError}.1011 * <p>1012 * Note that the order of extracted property/field values is consistent with the iteration order of the Iterable under1013 * test, for example if it's a {@link HashSet}, you won't be able to make any assumptions on the extracted values1014 * order.1015 * <hr>1016 * <p>1017 * Extracting also support maps, that is, instead of extracting values from an Object, it extract maps values1018 * corresponding to the given keys.1019 * <p>1020 * Example:1021 * <pre><code class='java'> Employee yoda = new Employee(1L, new Name("Yoda"), 800);1022 * Employee luke = new Employee(2L, new Name("Luke"), 22);1023 * Employee han = new Employee(3L, new Name("Han"), 31);1024 *1025 * // build two maps1026 * Map&lt;String, Employee&gt; map1 = new HashMap&lt;&gt;();1027 * map1.put("key1", yoda);1028 * map1.put("key2", luke);1029 *1030 * Map&lt;String, Employee&gt; map2 = new HashMap&lt;&gt;();1031 * map2.put("key1", yoda);1032 * map2.put("key2", han);1033 *1034 * // instead of a list of objects, we have a list of maps1035 * List&lt;Map&lt;String, Employee&gt;&gt; maps = asList(map1, map2);1036 *1037 * // extracting a property in that case = get values from maps using property as a key1038 * assertThat(maps).extracting(key2, Employee.class).containsExactly(luke, han);1039 *1040 * // non type safe version1041 * assertThat(maps).extracting("key2").containsExactly(luke, han);1042 * assertThat(maps).extracting("key1").containsExactly(yoda, yoda);1043 *1044 * // it works with several keys, extracted values being wrapped in a Tuple1045 * assertThat(maps).extracting("key1", "key2").containsExactly(tuple(yoda, luke), tuple(yoda, han));1046 *1047 * // unknown keys leads to null (map behavior)1048 * assertThat(maps).extracting("bad key").containsExactly(null, null);</code></pre>1049 *1050 * @param <P> the type of elements extracted.1051 * @param propertyOrField the property/field to extract from the Iterable under test1052 * @param extractingType type to return1053 * @return a new assertion object whose object under test is the list of extracted property/field values.1054 * @throws IntrospectionError if no field or property exists with the given name in one of the initial1055 * Iterable's element.1056 */1057 @CheckReturnValue1058 public <P> AbstractListAssert<?, List<? extends P>, P, ObjectAssert<P>> extracting(String propertyOrField,1059 Class<P> extractingType) {1060 @SuppressWarnings("unchecked")1061 List<P> values = (List<P>) FieldsOrPropertiesExtractor.extract(actual, byName(propertyOrField));1062 String extractedDescription = extractedDescriptionOf(propertyOrField);1063 String description = mostRelevantDescription(info.description(), extractedDescription);1064 return newListAssertInstanceForMethodsChangingElementType(values).as(description);1065 }1066 /**1067 * Extract the values of the given fields/properties from the Iterable's elements under test into a new Iterable composed1068 * of Tuples (a simple data structure), this new Iterable becoming the Iterable under test.1069 * <p>1070 * It allows you to test fields/properties of the Iterable's elements instead of testing the elements themselves,1071 * which can be much less work!1072 * <p>1073 * The Tuple data corresponds to the extracted values of the given fields/properties, for instance if you ask to1074 * extract "id", "name" and "email" then each Tuple data will be composed of id, name and email extracted from the1075 * element of the initial Iterable (the Tuple's data order is the same as the given fields/properties order).1076 * <p>1077 * Let's take an example to make things clearer :1078 * <pre><code class='java'> // Build a list of TolkienCharacter, a TolkienCharacter has a name, and age and a Race (a specific class)1079 * // they can be public field or properties, both can be extracted.1080 * List&lt;TolkienCharacter&gt; fellowshipOfTheRing = new ArrayList&lt;TolkienCharacter&gt;();1081 *1082 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Frodo&quot;, 33, HOBBIT));1083 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Sam&quot;, 38, HOBBIT));1084 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Gandalf&quot;, 2020, MAIA));1085 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Legolas&quot;, 1000, ELF));1086 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Pippin&quot;, 28, HOBBIT));1087 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Gimli&quot;, 139, DWARF));1088 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Aragorn&quot;, 87, MAN);1089 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Boromir&quot;, 37, MAN));1090 *1091 * // let's verify 'name' and 'age' of some TolkienCharacter in fellowshipOfTheRing :1092 * assertThat(fellowshipOfTheRing).extracting(&quot;name&quot;, &quot;age&quot;)1093 * .contains(tuple(&quot;Boromir&quot;, 37),1094 * tuple(&quot;Sam&quot;, 38),1095 * tuple(&quot;Legolas&quot;, 1000));1096 *1097 *1098 * // extract 'name', 'age' and Race name values :1099 * assertThat(fellowshipOfTheRing).extracting(&quot;name&quot;, &quot;age&quot;, &quot;race.name&quot;)1100 * .contains(tuple(&quot;Boromir&quot;, 37, &quot;Man&quot;),1101 * tuple(&quot;Sam&quot;, 38, &quot;Hobbit&quot;),1102 * tuple(&quot;Legolas&quot;, 1000, &quot;Elf&quot;));</code></pre>1103 *1104 * A property with the given name is looked for first, if it doesn't exist then a field with the given name is looked1105 * for, if the field does not exist an {@link IntrospectionError} is thrown, by default private fields are read but1106 * you can change this with {@link Assertions#setAllowComparingPrivateFields(boolean)}, trying to read a private field1107 * when it's not allowed leads to an {@link IntrospectionError}.1108 * <p>1109 * Note that the order of extracted property/field values is consistent with the iteration order of the Iterable under1110 * test, for example if it's a {@link HashSet}, you won't be able to make any assumptions on the extracted values1111 * order.1112 * <hr>1113 * <p>1114 * Extracting also support maps, that is, instead of extracting values from an Object, it extract maps values1115 * corresponding to the given keys.1116 * <p>1117 * Example:1118 * <pre><code class='java'> Employee yoda = new Employee(1L, new Name("Yoda"), 800);1119 * Employee luke = new Employee(2L, new Name("Luke"), 22);1120 * Employee han = new Employee(3L, new Name("Han"), 31);1121 *1122 * // build two maps1123 * Map&lt;String, Employee&gt; map1 = new HashMap&lt;&gt;();1124 * map1.put("key1", yoda);1125 * map1.put("key2", luke);1126 *1127 * Map&lt;String, Employee&gt; map2 = new HashMap&lt;&gt;();1128 * map2.put("key1", yoda);1129 * map2.put("key2", han);1130 *1131 * // instead of a list of objects, we have a list of maps1132 * List&lt;Map&lt;String, Employee&gt;&gt; maps = asList(map1, map2);1133 *1134 * // extracting a property in that case = get values from maps using property as a key1135 * assertThat(maps).extracting("key2").containsExactly(luke, han);1136 * assertThat(maps).extracting("key1").containsExactly(yoda, yoda);1137 *1138 * // it works with several keys, extracted values being wrapped in a Tuple1139 * assertThat(maps).extracting("key1", "key2").containsExactly(tuple(yoda, luke), tuple(yoda, han));1140 *1141 * // unknown keys leads to null (map behavior)1142 * assertThat(maps).extracting("bad key").containsExactly(null, null);</code></pre>1143 *1144 * @param propertiesOrFields the properties/fields to extract from the elements of the Iterable under test1145 * @return a new assertion object whose object under test is the list of Tuple with extracted properties/fields values1146 * as data.1147 * @throws IntrospectionError if one of the given name does not match a field or property in one of the initial1148 * Iterable's element.1149 */1150 @CheckReturnValue1151 public AbstractListAssert<?, List<? extends Tuple>, Tuple, ObjectAssert<Tuple>> extracting(String... propertiesOrFields) {1152 List<Tuple> values = FieldsOrPropertiesExtractor.extract(actual, byName(propertiesOrFields));1153 String extractedDescription = extractedDescriptionOf(propertiesOrFields);1154 String description = mostRelevantDescription(info.description(), extractedDescription);1155 return newListAssertInstanceForMethodsChangingElementType(values).as(description);1156 }1157 /**1158 * Extract the values from Iterable's elements under test by applying an extracting function on them. The returned1159 * iterable becomes a new object under test.1160 * <p>1161 * It allows to test values from the elements more safely than by using {@link #extracting(String)}, as it1162 * doesn't utilize introspection.1163 * <p>1164 * Let's have a look at an example :1165 * <pre><code class='java'> // Build a list of TolkienCharacter, a TolkienCharacter has a name, and age and a Race (a specific class)1166 * // they can be public field or properties, both can be extracted.1167 * List&lt;TolkienCharacter&gt; fellowshipOfTheRing = new ArrayList&lt;TolkienCharacter&gt;();1168 *1169 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Frodo&quot;, 33, HOBBIT));1170 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Sam&quot;, 38, HOBBIT));1171 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Gandalf&quot;, 2020, MAIA));1172 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Legolas&quot;, 1000, ELF));1173 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Pippin&quot;, 28, HOBBIT));1174 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Gimli&quot;, 139, DWARF));1175 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Aragorn&quot;, 87, MAN);1176 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Boromir&quot;, 37, MAN));1177 *1178 * // fellowship has hobbitses, right, my presioussss?1179 * assertThat(fellowshipOfTheRing).extracting(TolkienCharacter::getRace).contains(HOBBIT);</code></pre>1180 *1181 * Note that the order of extracted property/field values is consistent with the iteration order of the Iterable under1182 * test, for example if it's a {@link HashSet}, you won't be able to make any assumptions on the extracted values1183 * order.1184 *1185 * @param <V> the type of elements extracted.1186 * @param extractor the object transforming input object to desired one1187 * @return a new assertion object whose object under test is the list of values extracted1188 */1189 @CheckReturnValue1190 public <V> AbstractListAssert<?, List<? extends V>, V, ObjectAssert<V>> extracting(Function<? super ELEMENT, V> extractor) {1191 List<V> values = FieldsOrPropertiesExtractor.extract(actual, extractor);1192 return newListAssertInstanceForMethodsChangingElementType(values);1193 }1194 /**1195 * Extract the values from Iterable's elements under test by applying an extracting function (which might throw an1196 * exception) on them. The returned iterable becomes a new object under test.1197 * <p>1198 * Any checked exception raised in the extractor is rethrown wrapped in a {@link RuntimeException}.1199 * <p>1200 * It allows to test values from the elements more safely than by using {@link #extracting(String)}, as it1201 * doesn't utilize introspection.1202 * <p>1203 * Let's have a look at an example :1204 * <pre><code class='java'> // Build a list of TolkienCharacter, a TolkienCharacter has a name, and age and a Race (a specific class)1205 * // they can be public field or properties, both can be extracted.1206 * List&lt;TolkienCharacter&gt; fellowshipOfTheRing = new ArrayList&lt;TolkienCharacter&gt;();1207 *1208 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Frodo&quot;, 33, HOBBIT));1209 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Sam&quot;, 38, HOBBIT));1210 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Gandalf&quot;, 2020, MAIA));1211 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Legolas&quot;, 1000, ELF));1212 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Pippin&quot;, 28, HOBBIT));1213 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Gimli&quot;, 139, DWARF));1214 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Aragorn&quot;, 87, MAN);1215 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Boromir&quot;, 37, MAN));1216 *1217 * assertThat(fellowshipOfTheRing).extracting(input -&gt; {1218 * if (input.getAge() &lt; 20) {1219 * throw new Exception("age &lt; 20");1220 * }1221 * return input.getName();1222 * }).contains("Frodo");</code></pre>1223 *1224 * Note that the order of extracted property/field values is consistent with the iteration order of the Iterable under1225 * test, for example if it's a {@link HashSet}, you won't be able to make any assumptions on the extracted values1226 * order.1227 *1228 * @param <EXCEPTION> the exception type of {@link ThrowingExtractor}1229 * @param <V> the type of elements extracted.1230 * @param extractor the object transforming input object to desired one1231 * @return a new assertion object whose object under test is the list of values extracted1232 * @since 3.7.01233 */1234 @CheckReturnValue1235 public <V, EXCEPTION extends Exception> AbstractListAssert<?, List<? extends V>, V, ObjectAssert<V>> extracting(ThrowingExtractor<? super ELEMENT, V, EXCEPTION> extractor) {1236 List<V> values = FieldsOrPropertiesExtractor.extract(actual, extractor);1237 return newListAssertInstanceForMethodsChangingElementType(values);1238 }1239 /*1240 * Should be used after any methods changing the elements type like {@link #extracting(Function)} as it will propagate the1241 * correct1242 * assertions state, that is everything but the element comparator (since the element type has changed).1243 */1244 private <V> AbstractListAssert<?, List<? extends V>, V, ObjectAssert<V>> newListAssertInstanceForMethodsChangingElementType(List<V> values) {1245 if (actual instanceof SortedSet) {1246 // Reset the natural element comparator set when building an iterable assert instance for a SortedSet as it is likely not1247 // compatible with extracted values type, example with a SortedSet<Person> using a comparator on the Person's age, after1248 // extracting names we get a a List<String> which is mot suitable for the age comparator1249 usingDefaultElementComparator();1250 }1251 return newListAssertInstance(values).withAssertionState(myself);1252 }1253 /**1254 * Extract the Iterable values from Iterable's elements under test by applying an Iterable extracting function on them1255 * and concatenating the result lists. The returned iterable becomes a new object under test.1256 * <p>1257 * It allows testing the results of extracting values that are represented by Iterables.1258 * <p>1259 * For example:1260 * <pre><code class='java'> CartoonCharacter bart = new CartoonCharacter("Bart Simpson");1261 * CartoonCharacter lisa = new CartoonCharacter("Lisa Simpson");1262 * CartoonCharacter maggie = new CartoonCharacter("Maggie Simpson");1263 * CartoonCharacter homer = new CartoonCharacter("Homer Simpson");1264 * homer.getChildren().add(bart);1265 * homer.getChildren().add(lisa);1266 * homer.getChildren().add(maggie);1267 *1268 * CartoonCharacter pebbles = new CartoonCharacter("Pebbles Flintstone");1269 * CartoonCharacter fred = new CartoonCharacter("Fred Flintstone");1270 * fred.getChildren().add(pebbles);1271 *1272 * List&lt;CartoonCharacter&gt; parents = list(homer, fred);1273 *1274 * // check children property which is a List&lt;CartoonCharacter&gt;1275 * assertThat(parents).flatExtracting(CartoonCharacter::getChildren)1276 * .containsOnly(bart, lisa, maggie, pebbles);</code></pre>1277 *1278 * The order of extracted values is consistent with both the order of the collection itself, as well as the extracted1279 * collections.1280 *1281 * @param <V> the type of elements extracted.1282 * @param extractor the object transforming input object to an {@code Iterable} of desired ones1283 * @return a new assertion object whose object under test is the list of values extracted1284 * @throws NullPointerException if one of the {@code Iterable}'s element is null.1285 */1286 @CheckReturnValue1287 public <V> AbstractListAssert<?, List<? extends V>, V, ObjectAssert<V>> flatExtracting(Function<? super ELEMENT, ? extends Collection<V>> extractor) {1288 return doFlatExtracting(extractor);1289 }1290 /**1291 * Extract the Iterable values from Iterable's elements under test by applying an Iterable extracting function (which1292 * might throw a checked exception) on them and concatenating the result lists. The returned iterable becomes a new object1293 * under test.1294 * <p>1295 * It allows testing the results of extracting values that are represented by Iterables.1296 * <p>1297 * For example:1298 * <pre><code class='java'> CartoonCharacter bart = new CartoonCharacter("Bart Simpson");1299 * CartoonCharacter lisa = new CartoonCharacter("Lisa Simpson");1300 * CartoonCharacter maggie = new CartoonCharacter("Maggie Simpson");1301 * CartoonCharacter homer = new CartoonCharacter("Homer Simpson");1302 * homer.getChildren().add(bart);1303 * homer.getChildren().add(lisa);1304 * homer.getChildren().add(maggie);1305 *1306 * CartoonCharacter pebbles = new CartoonCharacter("Pebbles Flintstone");1307 * CartoonCharacter fred = new CartoonCharacter("Fred Flintstone");1308 * fred.getChildren().add(pebbles);1309 *1310 * List&lt;CartoonCharacter&gt; parents = list(homer, fred);1311 *1312 * // check children property where getChildren() can throw an Exception!1313 * assertThat(parents).flatExtracting(CartoonCharacter::getChildren)1314 * .containsOnly(bart, lisa, maggie, pebbles);</code></pre>1315 *1316 * The order of extracted values is consistent with both the order of the collection itself, as well as the extracted1317 * collections.1318 *1319 * @param <V> the type of elements extracted.1320 * @param <EXCEPTION> the exception type of {@link ThrowingExtractor}1321 * @param extractor the object transforming input object to an {@code Iterable} of desired ones1322 * @return a new assertion object whose object under test is the list of values extracted1323 * @throws NullPointerException if one of the {@code Iterable}'s element is null.1324 * @since 3.7.01325 */1326 @CheckReturnValue1327 public <V, EXCEPTION extends Exception> AbstractListAssert<?, List<? extends V>, V, ObjectAssert<V>> flatExtracting(ThrowingExtractor<? super ELEMENT, ? extends Collection<V>, EXCEPTION> extractor) {1328 return doFlatExtracting(extractor);1329 }1330 private <V> AbstractListAssert<?, List<? extends V>, V, ObjectAssert<V>> doFlatExtracting(Function<? super ELEMENT, ? extends Collection<V>> extractor) {1331 List<V> result = FieldsOrPropertiesExtractor.extract(actual, extractor).stream()1332 .flatMap(Collection::stream)1333 .collect(toList());1334 return newListAssertInstanceForMethodsChangingElementType(result);1335 }1336 /**1337 * Extract multiple values from each {@code Iterable}'s element according to the given {@code Function}s1338 * and concatenate/flatten the extracted values in a list that is used as the new object under test.1339 * <p>1340 * If extracted values were not flattened, instead of a simple list like (given 2 extractors) :1341 * <pre>element1.value1, element1.value2, element2.value1, element2.value2, ... </pre>1342 * we would get a list of list like :1343 * <pre>list(element1.value1, element1.value2), list(element2.value1, element2.value2), ... </pre>1344 * <p>1345 * Code example:1346 * <pre><code class='java'> // fellowshipOfTheRing is a List&lt;TolkienCharacter&gt;1347 *1348 * // values are extracted in order and flattened : age1, name1, age2, name2, age3 ...1349 * assertThat(fellowshipOfTheRing).flatExtracting(TolkienCharacter::getAge,1350 * TolkienCharacter::getName)1351 * .contains(33 ,"Frodo",1352 * 1000, "Legolas",1353 * 87, "Aragorn");</code></pre>1354 *1355 * The resulting extracted values list is ordered by {@code Iterable}'s element first and then extracted values,1356 * this is why is in the example that age values come before names.1357 *1358 * @param extractors all the extractors to apply on each actual {@code Iterable}'s elements1359 * @return a new assertion object whose object under test is a flattened list of all extracted values.1360 */1361 @CheckReturnValue1362 public AbstractListAssert<?, List<? extends Object>, Object, ObjectAssert<Object>> flatExtracting(@SuppressWarnings("unchecked") Function<? super ELEMENT, ?>... extractors) {1363 Stream<? extends ELEMENT> actualStream = stream(actual.spliterator(), false);1364 List<Object> result = actualStream.flatMap(element -> Stream.of(extractors)1365 .map(extractor -> extractor.apply(element)))1366 .collect(toList());1367 return newListAssertInstanceForMethodsChangingElementType(result);1368 }1369 /**1370 * Extract multiple values from each {@code Iterable}'s element according to the given {@link ThrowingExtractor}s1371 * and concatenate/flatten the extracted values in a list that is used as the new object under test.1372 * <p>1373 * If extracted values were not flattened, instead of a simple list like (given 2 extractors) :1374 * <pre>element1.value1, element1.value2, element2.value1, element2.value2, ... </pre>1375 * we would get a list of list like :1376 * <pre>list(element1.value1, element1.value2), list(element2.value1, element2.value2), ... </pre>1377 * <p>1378 * Code example:1379 * <pre><code class='java'> // fellowshipOfTheRing is a List&lt;TolkienCharacter&gt;1380 *1381 * // values are extracted in order and flattened : age1, name1, age2, name2, age3 ...1382 * assertThat(fellowshipOfTheRing).flatExtracting(input -&gt; {1383 * if (input.getAge() &lt; 20) {1384 * throw new Exception("age &lt; 20");1385 * }1386 * return input.getName();1387 * }, input2 -&gt; {1388 * if (input2.getAge() &lt; 20) {1389 * throw new Exception("age &lt; 20");1390 * }1391 * return input2.getAge();1392 * }).contains(33 ,"Frodo",1393 * 1000, "Legolas",1394 * 87, "Aragorn");</code></pre>1395 *1396 * The resulting extracted values list is ordered by {@code Iterable}'s element first and then extracted values,1397 * this is why is in the example that age values come before names.1398 *1399 * @param <EXCEPTION> the exception type of {@link ThrowingExtractor}1400 * @param extractors all the extractors to apply on each actual {@code Iterable}'s elements1401 * @return a new assertion object whose object under test is a flattened list of all extracted values.1402 * @since 3.7.01403 */1404 @CheckReturnValue1405 public <EXCEPTION extends Exception> AbstractListAssert<?, List<? extends Object>, Object, ObjectAssert<Object>> flatExtracting(@SuppressWarnings("unchecked") ThrowingExtractor<? super ELEMENT, ?, EXCEPTION>... extractors) {1406 Stream<? extends ELEMENT> actualStream = stream(actual.spliterator(), false);1407 List<Object> result = actualStream.flatMap(element -> Stream.of(extractors)1408 .map(extractor -> extractor.apply(element)))1409 .collect(toList());1410 return newListAssertInstanceForMethodsChangingElementType(result);1411 }1412 /**1413 * Extract from Iterable's elements the Iterable/Array values corresponding to the given property/field name and1414 * concatenate them into a single list becoming the new object under test.1415 * <p>1416 * It allows testing the elements of extracting values that are represented by iterables or arrays.1417 * <p>1418 * For example:1419 * <pre><code class='java'> CartoonCharacter bart = new CartoonCharacter("Bart Simpson");1420 * CartoonCharacter lisa = new CartoonCharacter("Lisa Simpson");1421 * CartoonCharacter maggie = new CartoonCharacter("Maggie Simpson");1422 * CartoonCharacter homer = new CartoonCharacter("Homer Simpson");1423 * homer.getChildren().add(bart);1424 * homer.getChildren().add(lisa);1425 * homer.getChildren().add(maggie);1426 *1427 * CartoonCharacter pebbles = new CartoonCharacter("Pebbles Flintstone");1428 * CartoonCharacter fred = new CartoonCharacter("Fred Flintstone");1429 * fred.getChildren().add(pebbles);1430 *1431 * List&lt;CartoonCharacter&gt; parents = list(homer, fred);1432 *1433 * // check children which is a List&lt;CartoonCharacter&gt;1434 * assertThat(parents).flatExtracting("children")1435 * .containsOnly(bart, lisa, maggie, pebbles);</code></pre>1436 *1437 * The order of extracted values is consisted with both the order of the collection itself, as well as the extracted1438 * collections.1439 *1440 * @param fieldOrPropertyName the object transforming input object to an Iterable of desired ones1441 * @return a new assertion object whose object under test is the list of values extracted1442 * @throws IllegalArgumentException if one of the extracted property value was not an array or an iterable.1443 */1444 @CheckReturnValue1445 public AbstractListAssert<?, List<? extends Object>, Object, ObjectAssert<Object>> flatExtracting(String fieldOrPropertyName) {1446 List<Object> extractedValues = newArrayList();1447 List<?> extractedGroups = FieldsOrPropertiesExtractor.extract(actual, byName(fieldOrPropertyName));1448 for (Object group : extractedGroups) {1449 // expecting group to be an iterable or an array1450 if (isArray(group)) {1451 int size = Array.getLength(group);1452 for (int i = 0; i < size; i++) {1453 extractedValues.add(Array.get(group, i));1454 }1455 } else if (group instanceof Iterable) {1456 Iterable<?> iterable = (Iterable<?>) group;1457 for (Object value : iterable) {1458 extractedValues.add(value);1459 }1460 } else {1461 CommonErrors.wrongElementTypeForFlatExtracting(group);1462 }1463 }1464 return newListAssertInstanceForMethodsChangingElementType(extractedValues);1465 }1466 /**1467 * Use the given {@link Function}s to extract the values from the {@link Iterable}'s elements into a new {@link Iterable}1468 * composed of {@link Tuple}s (a simple data structure containing the extracted values), this new {@link Iterable} becoming the1469 * object under test.1470 * <p>1471 * It allows you to test values from the {@link Iterable}'s elements instead of testing the elements themselves, which sometimes can be1472 * much less work!1473 * <p>1474 * The Tuple data corresponds to the extracted values from the Iterable's elements, for instance if you pass functions1475 * extracting "id", "name" and "email" values then each Tuple data will be composed of an id, a name and an email1476 * extracted from the element of the initial Iterable (the Tuple's data order is the same as the given functions1477 * order).1478 * <p>1479 * Let's take a look at an example to make things clearer :1480 * <pre><code class='java'> // Build a list of TolkienCharacter, a TolkienCharacter has a name, and age and a Race (a specific class)1481 * // they can be public field or properties, both can be extracted.1482 * List&lt;TolkienCharacter&gt; fellowshipOfTheRing = new ArrayList&lt;TolkienCharacter&gt;();1483 *1484 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Frodo&quot;, 33, HOBBIT));1485 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Sam&quot;, 38, HOBBIT));1486 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Gandalf&quot;, 2020, MAIA));1487 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Legolas&quot;, 1000, ELF));1488 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Pippin&quot;, 28, HOBBIT));1489 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Gimli&quot;, 139, DWARF));1490 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Aragorn&quot;, 87, MAN);1491 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Boromir&quot;, 37, MAN));1492 *1493 * // let's verify 'name', 'age' and Race of some TolkienCharacter in fellowshipOfTheRing :1494 * assertThat(fellowshipOfTheRing).extracting(TolkienCharacter::getName,1495 * character -&gt; character.getAge(),1496 * TolkienCharacter::getRace)1497 * .containsOnly(tuple(&quot;Frodo&quot;, 33, HOBBIT),1498 * tuple(&quot;Sam&quot;, 38, HOBBIT),1499 * tuple(&quot;Gandalf&quot;, 2020, MAIA),1500 * tuple(&quot;Legolas&quot;, 1000, ELF),1501 * tuple(&quot;Pippin&quot;, 28, HOBBIT),1502 * tuple(&quot;Gimli&quot;, 139, DWARF),1503 * tuple(&quot;Aragorn&quot;, 87, MAN),1504 * tuple(&quot;Boromir&quot;, 37, MAN));</code></pre>1505 * You can use lambda expression or a method reference to extract the expected values.1506 * <p>1507 * Use {@link Tuple#tuple(Object...)} to initialize the expected values.1508 * <p>1509 * Note that the order of the extracted tuples list is consistent with the iteration order of the Iterable under test,1510 * for example if it's a {@link HashSet}, you won't be able to make any assumptions on the extracted tuples order.1511 *1512 * @param extractors the extractor functions to extract a value from an element of the Iterable under test.1513 * @return a new assertion object whose object under test is the list of Tuples containing the extracted values.1514 */1515 @CheckReturnValue1516 public AbstractListAssert<?, List<? extends Tuple>, Tuple, ObjectAssert<Tuple>> extracting(@SuppressWarnings("unchecked") Function<? super ELEMENT, ?>... extractors) {1517 // combine all extractors into one function1518 Function<ELEMENT, Tuple> tupleExtractor = objectToExtractValueFrom -> new Tuple(Stream.of(extractors)1519 .map(extractor -> extractor.apply(objectToExtractValueFrom))1520 .toArray());1521 List<Tuple> tuples = stream(actual.spliterator(), false).map(tupleExtractor)1522 .collect(toList());1523 return newListAssertInstanceForMethodsChangingElementType(tuples);1524 }1525 /**1526 * Extract the given property/field values from each {@code Iterable}'s element and1527 * flatten the extracted values in a list that is used as the new object under test.1528 * <p>1529 * Given 2 properties, if the extracted values were not flattened, instead having a simple list like :1530 * <pre>element1.value1, element1.value2, element2.value1, element2.value2, ... </pre>1531 * ... we would get a list of list :1532 * <pre>list(element1.value1, element1.value2), list(element2.value1, element2.value2), ... </pre>1533 * <p>1534 * Code example:1535 * <pre><code class='java'> // fellowshipOfTheRing is a List&lt;TolkienCharacter&gt;1536 *1537 * // values are extracted in order and flattened : age1, name1, age2, name2, age3 ...1538 * assertThat(fellowshipOfTheRing).flatExtracting("age", "name")1539 * .contains(33 ,"Frodo",1540 * 1000, "Legolas",1541 * 87, "Aragorn");</code></pre>1542 *1543 * @param fieldOrPropertyNames the field and/or property names to extract from each actual {@code Iterable}'s element1544 * @return a new assertion object whose object under test is a flattened list of all extracted values.1545 * @throws IllegalArgumentException if fieldOrPropertyNames vararg is null or empty1546 * @since 2.5.0 / 3.5.01547 */1548 @CheckReturnValue1549 public AbstractListAssert<?, List<? extends Object>, Object, ObjectAssert<Object>> flatExtracting(String... fieldOrPropertyNames) {1550 List<Object> extractedValues = FieldsOrPropertiesExtractor.extract(actual, byName(fieldOrPropertyNames)).stream()1551 .flatMap(tuple -> tuple.toList().stream())1552 .collect(toList());1553 return newListAssertInstanceForMethodsChangingElementType(extractedValues);1554 }1555 /**1556 * {@inheritDoc}1557 */1558 @Override1559 public SELF containsExactlyElementsOf(Iterable<? extends ELEMENT> iterable) {1560 return containsExactly(toArray(iterable));1561 }1562 /**1563 * {@inheritDoc}1564 */1565 @Deprecated1566 @Override1567 public SELF containsOnlyElementsOf(Iterable<? extends ELEMENT> iterable) {1568 return containsOnly(toArray(iterable));1569 }1570 /**1571 * {@inheritDoc}1572 */1573 @Override1574 public SELF containsOnlyOnceElementsOf(Iterable<? extends ELEMENT> iterable) {1575 return containsOnlyOnce(toArray(iterable));1576 }1577 /**1578 * {@inheritDoc}1579 */1580 @Override1581 public SELF hasSameElementsAs(Iterable<? extends ELEMENT> iterable) {1582 // containsOnlyElementsOf is deprecated so we use its implementation1583 return containsOnly(toArray(iterable));1584 }1585 /**1586 * Allows to set a comparator to compare properties or fields of elements with the given names.1587 * A typical usage is for comparing fields of numeric type at a given precision.1588 * <p>1589 * To be used, comparators need to be specified by this method <b>before</b> calling any of:1590 * <ul>1591 * <li>{@link #usingFieldByFieldElementComparator}</li>1592 * <li>{@link #usingElementComparatorOnFields}</li>1593 * <li>{@link #usingElementComparatorIgnoringFields}</li>1594 * <li>{@link #usingRecursiveFieldByFieldElementComparator}</li>1595 * </ul>1596 * <p>1597 * Comparators specified by this method have precedence over comparators specified by1598 * {@link #usingComparatorForElementFieldsWithType(Comparator, Class) usingComparatorForElementFieldsWithType}.1599 * <p>1600 * Example:1601 *1602 * <pre><code class='java'> public class TolkienCharacter {1603 * private String name;1604 * private double height;1605 * // constructor omitted1606 * }1607 *1608 * TolkienCharacter frodo = new TolkienCharacter(&quot;Frodo&quot;, 1.2);1609 * TolkienCharacter tallerFrodo = new TolkienCharacter(&quot;Frodo&quot;, 1.3);1610 * TolkienCharacter reallyTallFrodo = new TolkienCharacter(&quot;Frodo&quot;, 1.9);1611 *1612 * Comparator&lt;Double&gt; closeEnough = new Comparator&lt;Double&gt;() {1613 * double precision = 0.5;1614 * public int compare(Double d1, Double d2) {1615 * return Math.abs(d1 - d2) &lt;= precision ? 0 : 1;1616 * }1617 * };1618 *1619 * // assertions will pass1620 * assertThat(asList(frodo)).usingComparatorForElementFieldsWithNames(closeEnough, &quot;height&quot;)1621 * .usingFieldByFieldElementComparator()1622 * .contains(tallerFrodo);1623 *1624 * assertThat(asList(frodo)).usingComparatorForElementFieldsWithNames(closeEnough, &quot;height&quot;)1625 * .usingElementComparatorOnFields(&quot;height&quot;)1626 * .contains(tallerFrodo);1627 *1628 * assertThat(asList(frodo)).usingComparatorForElementFieldsWithNames(closeEnough, &quot;height&quot;)1629 * .usingElementComparatorIgnoringFields(&quot;name&quot;)1630 * .contains(tallerFrodo);1631 *1632 * assertThat(asList(frodo)).usingComparatorForElementFieldsWithNames(closeEnough, &quot;height&quot;)1633 * .usingRecursiveFieldByFieldElementComparator()1634 * .contains(tallerFrodo);1635 *1636 * // assertion will fail1637 * assertThat(asList(frodo)).usingComparatorForElementFieldsWithNames(closeEnough, &quot;height&quot;)1638 * .usingFieldByFieldElementComparator()1639 * .containsExactly(reallyTallFrodo);</code></pre>1640 *1641 * @param <T> the type of elements to compare.1642 * @param comparator the {@link java.util.Comparator} to use1643 * @param elementPropertyOrFieldNames the names of the properties and/or fields of the elements the comparator should be used for1644 * @return {@code this} assertions object1645 * @since 2.5.0 / 3.5.01646 */1647 @CheckReturnValue1648 public <T> SELF usingComparatorForElementFieldsWithNames(Comparator<T> comparator,1649 String... elementPropertyOrFieldNames) {1650 for (String elementPropertyOrField : elementPropertyOrFieldNames) {1651 comparatorsForElementPropertyOrFieldNames.put(elementPropertyOrField, comparator);1652 }1653 return myself;1654 }1655 /**1656 * Allows to set a specific comparator to compare properties or fields of elements with the given type.1657 * A typical usage is for comparing fields of numeric type at a given precision.1658 * <p>1659 * To be used, comparators need to be specified by this method <b>before</b> calling any of:1660 * <ul>1661 * <li>{@link #usingFieldByFieldElementComparator}</li>1662 * <li>{@link #usingElementComparatorOnFields}</li>1663 * <li>{@link #usingElementComparatorIgnoringFields}</li>1664 * <li>{@link #usingRecursiveFieldByFieldElementComparator}</li>1665 * </ul>1666 * <p>1667 * Comparators specified by {@link #usingComparatorForElementFieldsWithNames(Comparator, String...) usingComparatorForElementFieldsWithNames}1668 * have precedence over comparators specified by this method.1669 * <p>1670 * Example:1671 * <pre><code class='java'> public class TolkienCharacter {1672 * private String name;1673 * private double height;1674 * // constructor omitted1675 * }1676 * TolkienCharacter frodo = new TolkienCharacter(&quot;Frodo&quot;, 1.2);1677 * TolkienCharacter tallerFrodo = new TolkienCharacter(&quot;Frodo&quot;, 1.3);1678 * TolkienCharacter reallyTallFrodo = new TolkienCharacter(&quot;Frodo&quot;, 1.9);1679 *1680 * Comparator&lt;Double&gt; closeEnough = new Comparator&lt;Double&gt;() {1681 * double precision = 0.5;1682 * public int compare(Double d1, Double d2) {1683 * return Math.abs(d1 - d2) &lt;= precision ? 0 : 1;1684 * }1685 * };1686 *1687 * // assertions will pass1688 * assertThat(Arrays.asList(frodo)).usingComparatorForElementFieldsWithType(closeEnough, Double.class)1689 * .usingFieldByFieldElementComparator()1690 * .contains(tallerFrodo);1691 *1692 * assertThat(Arrays.asList(frodo)).usingComparatorForElementFieldsWithType(closeEnough, Double.class)1693 * .usingElementComparatorOnFields(&quot;height&quot;)1694 * .contains(tallerFrodo);1695 *1696 * assertThat(Arrays.asList(frodo)).usingComparatorForElementFieldsWithType(closeEnough, Double.class)1697 * .usingElementComparatorIgnoringFields(&quot;name&quot;)1698 * .contains(tallerFrodo);1699 *1700 * assertThat(Arrays.asList(frodo)).usingComparatorForElementFieldsWithType(closeEnough, Double.class)1701 * .usingRecursiveFieldByFieldElementComparator()1702 * .contains(tallerFrodo);1703 *1704 * // assertion will fail1705 * assertThat(Arrays.asList(frodo)).usingComparatorForElementFieldsWithType(closeEnough, Double.class)1706 * .usingFieldByFieldElementComparator()1707 * .contains(reallyTallFrodo);</code></pre>1708 *1709 * @param <T> the type of elements to compare.1710 * @param comparator the {@link java.util.Comparator} to use1711 * @param type the {@link java.lang.Class} of the type of the element fields the comparator should be used for1712 * @return {@code this} assertions object1713 * @since 2.5.0 / 3.5.01714 */1715 @CheckReturnValue1716 public <T> SELF usingComparatorForElementFieldsWithType(Comparator<T> comparator, Class<T> type) {1717 getComparatorsForElementPropertyOrFieldTypes().put(type, comparator);1718 return myself;1719 }1720 /**1721 * Allows to set a specific comparator for the given type of elements or their fields.1722 * Extends {@link #usingComparatorForElementFieldsWithType} by applying comparator specified for given type1723 * to elements themselves, not only to their fields.1724 * <p>1725 * Usage of this method affects comparators set by next methods:1726 * <ul>1727 * <li>{@link #usingFieldByFieldElementComparator}</li>1728 * <li>{@link #usingElementComparatorOnFields}</li>1729 * <li>{@link #usingElementComparatorIgnoringFields}</li>1730 * <li>{@link #usingRecursiveFieldByFieldElementComparator}</li>1731 * </ul>1732 * <p>1733 * Example:1734 * <pre><code class='java'>1735 * // assertion will pass1736 * assertThat(asList("some", new BigDecimal("4.2")))1737 * .usingComparatorForType(BIG_DECIMAL_COMPARATOR, BigDecimal.class)1738 * .contains(new BigDecimal("4.20"));1739 * </code></pre>1740 *1741 * @param <T> the type of elements to compare.1742 * @param comparator the {@link java.util.Comparator} to use1743 * @param type the {@link java.lang.Class} of the type of the element or element fields the comparator should be used for1744 * @return {@code this} assertions object1745 * @since 2.9.0 / 3.9.01746 */1747 @CheckReturnValue1748 public <T> SELF usingComparatorForType(Comparator<T> comparator, Class<T> type) {1749 if (iterables.getComparator() == null) {1750 usingElementComparator(new ExtendedByTypesComparator(getComparatorsByType()));1751 }1752 getComparatorsForElementPropertyOrFieldTypes().put(type, comparator);1753 getComparatorsByType().put(type, comparator);1754 return myself;1755 }1756 /**1757 * Use field/property by field/property comparison (including inherited fields/properties) instead of relying on1758 * actual type A <code>equals</code> method to compare group elements for incoming assertion checks. Private fields1759 * are included but this can be disabled using {@link Assertions#setAllowExtractingPrivateFields(boolean)}.1760 * <p>1761 * This can be handy if <code>equals</code> method of the objects to compare does not suit you.1762 * <p>1763 * Note that the comparison is <b>not</b> recursive, if one of the fields/properties is an Object, it will be compared1764 * to the other field/property using its <code>equals</code> method.1765 * <p>1766 * You can specify a custom comparator per name or type of element field with1767 * {@link #usingComparatorForElementFieldsWithNames(Comparator, String...)}1768 * and {@link #usingComparatorForElementFieldsWithType(Comparator, Class)}.1769 * <p>1770 * Example:1771 * <pre><code class='java'> TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT);1772 * TolkienCharacter frodoClone = new TolkienCharacter("Frodo", 33, HOBBIT);1773 *1774 * // Fail if equals has not been overridden in TolkienCharacter as equals default implementation only compares references1775 * assertThat(newArrayList(frodo)).contains(frodoClone);1776 *1777 * // frodo and frodoClone are equals when doing a field by field comparison.1778 * assertThat(newArrayList(frodo)).usingFieldByFieldElementComparator().contains(frodoClone);</code></pre>1779 *1780 * @return {@code this} assertion object.1781 */1782 @CheckReturnValue1783 public SELF usingFieldByFieldElementComparator() {1784 return usingExtendedByTypesElementComparator(new FieldByFieldComparator(comparatorsForElementPropertyOrFieldNames,1785 getComparatorsForElementPropertyOrFieldTypes()));1786 }1787 /**1788 * Use a recursive field/property by field/property comparison (including inherited fields/properties)1789 * instead of relying on actual type <code>equals</code> method to compare group elements for incoming1790 * assertion checks. This can be useful if actual's {@code equals} implementation does not suit you.1791 * <p>1792 * The recursive property/field comparison is <b>not</b> applied on fields having a custom {@code equals}1793 * implementation, i.e. the overridden {@code equals} method will be used instead of a field/property by field/property1794 * comparison.1795 * <p>1796 * The recursive comparison handles cycles.1797 * <p>1798 * You can specify a custom comparator per (nested) name or type of element field with1799 * {@link #usingComparatorForElementFieldsWithNames(Comparator, String...) usingComparatorForElementFieldsWithNames}1800 * and {@link #usingComparatorForElementFieldsWithType(Comparator, Class) usingComparatorForElementFieldsWithType}.1801 * <p>1802 * The objects to compare can be of different types but must have the same properties/fields. For example if actual1803 * object has a {@code name} String field, the other object must also have one.1804 * <p>1805 * If an object has a field and a property with the same name, the property value will be used over the field.1806 * <p>1807 * Example:1808 * <pre><code class='java'> TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT);1809 * TolkienCharacter pippin = new TolkienCharacter("Pippin", 28, HOBBIT);1810 * frodo.setFriend(pippin);1811 * pippin.setFriend(frodo);1812 *1813 * TolkienCharacter frodoClone = new TolkienCharacter("Frodo", 33, HOBBIT);1814 * TolkienCharacter pippinClone = new TolkienCharacter("Pippin", 28, HOBBIT);1815 * frodoClone.setFriend(pippinClone);1816 * pippinClone.setFriend(frodoClone);1817 *1818 * List&lt;TolkienCharacter&gt; hobbits = Arrays.asList(frodo, pippin);1819 *1820 * // fails if equals has not been overridden in TolkienCharacter as it would compares object references1821 * assertThat(hobbits).contains(frodoClone, pippinClone);1822 *1823 * // frodo/frodoClone and pippin/pippinClone are equals when doing a recursive property/field by property/field comparison1824 * assertThat(hobbits).usingRecursiveFieldByFieldElementComparator()1825 * .contains(frodoClone, pippinClone);</code>1826 * </pre>1827 *1828 * @return {@code this} assertion object.1829 * @since 2.5.0 / 3.5.01830 */1831 @CheckReturnValue1832 public SELF usingRecursiveFieldByFieldElementComparator() {1833 return usingExtendedByTypesElementComparator(new RecursiveFieldByFieldComparator(comparatorsForElementPropertyOrFieldNames,1834 getComparatorsForElementPropertyOrFieldTypes()));1835 }1836 /**1837 * Enable using a recursive field by field comparison strategy similar to {@link #usingRecursiveComparison()} but contrary to the latter <b>you can chain any iterable assertions after this method</b> (this is why this method exists).1838 * <p>1839 * The given {@link RecursiveComparisonConfiguration} is used to tweak the comparison behavior, for example by {@link RecursiveComparisonConfiguration#ignoreCollectionOrder(boolean) ignoring collection order}.1840 * <p>1841 * <b>Warning:</b> the comparison won't use any comparators set with:1842 * <ul>1843 * <li>{@link #usingComparatorForType(Comparator, Class)}</li>1844 * <li>{@link #withTypeComparators(TypeComparators)}</li>1845 * <li>{@link #usingComparatorForElementFieldsWithType(Comparator, Class)}</li>1846 * <li>{@link #withComparatorsForElementPropertyOrFieldTypes(TypeComparators)}</li>1847 * <li>{@link #usingComparatorForElementFieldsWithNames(Comparator, String...)}</li>1848 * <li>{@link #withComparatorsForElementPropertyOrFieldNames(Map)}</li>1849 * </ul>1850 * <p>1851 * These features (and many more) are provided through {@link RecursiveComparisonConfiguration} with:1852 * <ul>1853 * <li>{@link RecursiveComparisonConfiguration#registerComparatorForType(Comparator, Class) registerComparatorForType(Comparator, Class)} / {@link RecursiveComparisonConfiguration.Builder#withComparatorForType(Comparator, Class) withComparatorForType(Comparator, Class)} (using {@link RecursiveComparisonConfiguration.Builder})</li>1854 * <li>{@link RecursiveComparisonConfiguration#registerEqualsForType(java.util.function.BiPredicate, Class) registerEqualsForType(BiPredicate, Class)} / {@link RecursiveComparisonConfiguration.Builder#withComparatorForType(Comparator, Class) withComparatorForType(Comparator, Class)} (using {@link RecursiveComparisonConfiguration.Builder})</li>1855 * <li>{@link RecursiveComparisonConfiguration#registerComparatorForFields(Comparator, String...) registerComparatorForFields(Comparator comparator, String... fields)} / {@link RecursiveComparisonConfiguration.Builder#withComparatorForFields(Comparator, String...) withComparatorForField(Comparator comparator, String... fields)} (using {@link RecursiveComparisonConfiguration.Builder})</li>1856 * </ul>1857 * <p>1858 * RecursiveComparisonConfiguration exposes a {@link RecursiveComparisonConfiguration.Builder builder} to ease setting the comparison behaviour,1859 * call {@link RecursiveComparisonConfiguration#builder() RecursiveComparisonConfiguration.builder()} to start building your configuration.1860 * <p>1861 * There are differences between this approach and {@link #usingRecursiveComparison()}:1862 * <ul>1863 * <li>contrary to {@link RecursiveComparisonAssert}, you can chain any iterable assertions after this method.</li>1864 * <li>no comparators registered with {@link AbstractIterableAssert#usingComparatorForType(Comparator, Class)} will be used, you need to register them in the configuration object.</li>1865 * <li>the assertion errors won't be as detailed as {@link RecursiveComparisonAssert#isEqualTo(Object)} which shows the field differences.</li>1866 * </ul>1867 * <p>1868 * This last point makes sense, take the {@link #contains(Object...)} assertion, it would not be relevant to report the differences of all the iterable's elements differing from the values to look for.1869 * <p>1870 * Example:1871 * <pre><code class='java'> public class Person {1872 * String name;1873 * boolean hasPhd;1874 * }1875 *1876 * public class Doctor {1877 * String name;1878 * boolean hasPhd;1879 * }1880 *1881 * Doctor drSheldon = new Doctor("Sheldon Cooper", true);1882 * Doctor drLeonard = new Doctor("Leonard Hofstadter", true);1883 * Doctor drRaj = new Doctor("Raj Koothrappali", true);1884 *1885 * Person sheldon = new Person("Sheldon Cooper", false);1886 * Person leonard = new Person("Leonard Hofstadter", false);1887 * Person raj = new Person("Raj Koothrappali", false);1888 * Person howard = new Person("Howard Wolowitz", false);1889 *1890 * List&lt;Doctor&gt; doctors = list(drSheldon, drLeonard, drRaj);1891 * List&lt;Person&gt; people = list(sheldon, leonard, raj);1892 *1893 * RecursiveComparisonConfiguration configuration = RecursiveComparisonConfiguration.builder()1894 * .withIgnoredFields​("hasPhd");1895 *1896 * // assertion succeeds as both lists contains equivalent items in order.1897 * assertThat(doctors).usingRecursiveFieldByFieldElementComparator(configuration)1898 * .contains(sheldon);1899 *1900 * // assertion fails because leonard names are different.1901 * leonard.setName("Leonard Ofstater");1902 * assertThat(doctors).usingRecursiveFieldByFieldElementComparator(configuration)1903 * .contains(leonard);1904 *1905 * // assertion fails because howard is missing and leonard is not expected.1906 * people = list(howard, sheldon, raj)1907 * assertThat(doctors).usingRecursiveFieldByFieldElementComparator(configuration)1908 * .contains(howard);</code></pre>1909 *1910 * A detailed documentation for the recursive comparison is available here: <a href="https://assertj.github.io/doc/#assertj-core-recursive-comparison">https://assertj.github.io/doc/#assertj-core-recursive-comparison</a>.1911 * <p>1912 * The default recursive comparison behavior is {@link RecursiveComparisonConfiguration configured} as follows:1913 * <ul>1914 * <li> different types of iterable can be compared by default, this allows to compare for example an {@code List<Person>} and a {@code LinkedHashSet<PersonDto>}.<br>1915 * This behavior can be turned off by calling {@link RecursiveComparisonAssert#withStrictTypeChecking() withStrictTypeChecking}.</li>1916 * <li>overridden equals methods are used in the comparison (unless stated otherwise - see <a href="https://assertj.github.io/doc/#assertj-core-recursive-comparison-ignoring-equals">https://assertj.github.io/doc/#assertj-core-recursive-comparison-ignoring-equals</a>)</li>1917 * <li>the following types are compared with these comparators:1918 * <ul>1919 * <li>{@code java.lang.Double}: {@code DoubleComparator} with precision of 1.0E-15</li>1920 * <li>{@code java.lang.Float}: {@code FloatComparator }with precision of 1.0E-6</li>1921 * </ul>1922 * </li>1923 * </ul>1924 * <p>1925 * Another point worth mentioning: <b>elements order does matter if the expected iterable is ordered</b>, for example comparing a {@code Set<Person>} to a {@code List<Person>} fails as {@code List} is ordered and {@code Set} is not.<br>1926 * The ordering can be ignored by calling {@link RecursiveComparisonAssert#ignoringCollectionOrder ignoringCollectionOrder} allowing ordered/unordered iterable comparison, note that {@link RecursiveComparisonAssert#ignoringCollectionOrder ignoringCollectionOrder} is applied recursively on any nested iterable fields, if this behavior is too generic,1927 * use the more fine grained {@link RecursiveComparisonAssert#ignoringCollectionOrderInFields(String...) ignoringCollectionOrderInFields} or1928 * {@link RecursiveComparisonAssert#ignoringCollectionOrderInFieldsMatchingRegexes(String...) ignoringCollectionOrderInFieldsMatchingRegexes}.1929 *1930 * @param configuration the recursive comparison configuration.1931 *1932 * @return {@code this} assertion object.1933 * @since 3.17.01934 * @see RecursiveComparisonConfiguration1935 */1936 public SELF usingRecursiveFieldByFieldElementComparator(RecursiveComparisonConfiguration configuration) {1937 return usingElementComparator(new ConfigurableRecursiveFieldByFieldComparator(configuration));1938 }1939 /**1940 * Enable using a recursive field by field comparison strategy when calling the chained {@link RecursiveComparisonAssert},1941 * <p>1942 * There are differences between this approach and {@link #usingRecursiveFieldByFieldElementComparator(RecursiveComparisonConfiguration)}:1943 * <ul>1944 * <li>you can only chain {@link RecursiveComparisonAssert} assertions (basically {@link RecursiveComparisonAssert#isEqualTo(Object) isEqualTo}) and (basically {@link RecursiveComparisonAssert#isNotEqualTo(Object) isNotEqualTo}), no iterable assertions.</li>1945 * <li>{@link RecursiveComparisonAssert#isEqualTo(Object) isEqualTo} assertion error will report all field differences (very detailed).</li>1946 * <li>no comparators registered with {@link AbstractIterableAssert#usingComparatorForType(Comparator, Class)} will be used, you need to register them in chained call like {@link RecursiveComparisonAssert#withComparatorForType(Comparator, Class)}.</li>1947 * </ul>1948 * <p>1949 * If you need to chain iterable assertions using recursive comparisons call {@link #usingRecursiveFieldByFieldElementComparator(RecursiveComparisonConfiguration)} instead.1950 * <p>1951 * Example:1952 * <pre><code class='java'> public class Person {1953 * String name;1954 * boolean hasPhd;1955 * }1956 *1957 * public class Doctor {1958 * String name;1959 * boolean hasPhd;1960 * }1961 *1962 * Doctor drSheldon = new Doctor("Sheldon Cooper", true);1963 * Doctor drLeonard = new Doctor("Leonard Hofstadter", true);1964 * Doctor drRaj = new Doctor("Raj Koothrappali", true);1965 *1966 * Person sheldon = new Person("Sheldon Cooper", true);1967 * Person leonard = new Person("Leonard Hofstadter", true);1968 * Person raj = new Person("Raj Koothrappali", true);1969 * Person howard = new Person("Howard Wolowitz", false);1970 *1971 * List&lt;Doctor&gt; doctors = Arrays.asList(drSheldon, drLeonard, drRaj);1972 * List&lt;Person&gt; people = Arrays.asList(sheldon, leonard, raj);1973 *1974 * // assertion succeeds as both lists contains equivalent items in order.1975 * assertThat(doctors).usingRecursiveComparison()1976 * .isEqualTo(people);1977 *1978 * // assertion fails because leonard names are different.1979 * leonard.setName("Leonard Ofstater");1980 * assertThat(doctors).usingRecursiveComparison()1981 * .isEqualTo(people);1982 *1983 * // assertion fails because howard is missing and leonard is not expected.1984 * people = Arrays.asList(howard, sheldon, raj)1985 * assertThat(doctors).usingRecursiveComparison()1986 * .isEqualTo(people);</code></pre>1987 *1988 * A detailed documentation for the recursive comparison is available here: <a href="https://assertj.github.io/doc/#assertj-core-recursive-comparison">https://assertj.github.io/doc/#assertj-core-recursive-comparison</a>.1989 * <p>1990 * The default recursive comparison behavior is {@link RecursiveComparisonConfiguration configured} as follows:1991 * <ul>1992 * <li> different types of iterable can be compared by default, this allows to compare for example an {@code List<Person>} and a {@code LinkedHashSet<PersonDto>}.<br>1993 * This behavior can be turned off by calling {@link RecursiveComparisonAssert#withStrictTypeChecking() withStrictTypeChecking}.</li>1994 * <li>overridden equals methods are used in the comparison (unless stated otherwise - see <a href="https://assertj.github.io/doc/#assertj-core-recursive-comparison-ignoring-equals">https://assertj.github.io/doc/#assertj-core-recursive-comparison-ignoring-equals</a>)</li>1995 * <li>the following types are compared with these comparators:1996 * <ul>1997 * <li>{@code java.lang.Double}: {@code DoubleComparator} with precision of 1.0E-15</li>1998 * <li>{@code java.lang.Float}: {@code FloatComparator }with precision of 1.0E-6</li>1999 * </ul>2000 * </li>2001 * </ul>2002 * <p>2003 * Another point worth mentioning: <b>elements order does matter if the expected iterable is ordered</b>, for example comparing a {@code Set<Person>} to a {@code List<Person>} fails as {@code List} is ordered and {@code Set} is not.<br>2004 * The ordering can be ignored by calling {@link RecursiveComparisonAssert#ignoringCollectionOrder ignoringCollectionOrder} allowing ordered/unordered iterable comparison, note that {@link RecursiveComparisonAssert#ignoringCollectionOrder ignoringCollectionOrder} is applied recursively on any nested iterable fields, if this behavior is too generic,2005 * use the more fine grained {@link RecursiveComparisonAssert#ignoringCollectionOrderInFields(String...) ignoringCollectionOrderInFields} or2006 * {@link RecursiveComparisonAssert#ignoringCollectionOrderInFieldsMatchingRegexes(String...) ignoringCollectionOrderInFieldsMatchingRegexes}.2007 * <p>2008 * At the moment, only `isEqualTo` can be chained after this method but there are plans to provide assertions.2009 *2010 * @return a new {@link RecursiveComparisonAssert} instance2011 * @see RecursiveComparisonConfiguration RecursiveComparisonConfiguration2012 */2013 @Override2014 @Beta2015 public RecursiveComparisonAssert<?> usingRecursiveComparison() {2016 // overridden for javadoc and to make this method public2017 return super.usingRecursiveComparison();2018 }2019 /**2020 * Same as {@link #usingRecursiveComparison()} but allows to specify your own {@link RecursiveComparisonConfiguration}.2021 * <p>2022 * Another difference is that any comparators previously registered with {@link AbstractIterableAssert#usingComparatorForType(Comparator, Class)} will be used in the comparison.2023 *2024 * @param recursiveComparisonConfiguration the {@link RecursiveComparisonConfiguration} used in the chained {@link RecursiveComparisonAssert#isEqualTo(Object) isEqualTo} assertion.2025 *2026 * @return a new {@link RecursiveComparisonAssert} instance built with the given {@link RecursiveComparisonConfiguration}.2027 */2028 @Override2029 public RecursiveComparisonAssert<?> usingRecursiveComparison(RecursiveComparisonConfiguration recursiveComparisonConfiguration) {2030 return super.usingRecursiveComparison(recursiveComparisonConfiguration).withTypeComparators(comparatorsByType);2031 }2032 /**2033 * Use field/property by field/property comparison on the <b>given fields/properties only</b> (including inherited2034 * fields/properties) instead of relying on actual type A <code>equals</code> method to compare group elements for2035 * incoming assertion checks. Private fields are included but this can be disabled using2036 * {@link Assertions#setAllowExtractingPrivateFields(boolean)}.2037 * <p>2038 * This can be handy if <code>equals</code> method of the objects to compare does not suit you.2039 * <p>2040 * You can specify a custom comparator per name or type of element field with2041 * {@link #usingComparatorForElementFieldsWithNames(Comparator, String...)}2042 * and {@link #usingComparatorForElementFieldsWithType(Comparator, Class)}.2043 * <p>2044 * Note that the comparison is <b>not</b> recursive, if one of the fields/properties is an Object, it will be compared2045 * to the other field/property using its <code>equals</code> method.2046 * </p>2047 * Example:2048 * <pre><code class='java'> TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT);2049 * TolkienCharacter sam = new TolkienCharacter("Sam", 38, HOBBIT);2050 *2051 * // frodo and sam both are hobbits, so they are equals when comparing only race2052 * assertThat(newArrayList(frodo)).usingElementComparatorOnFields("race").contains(sam); // OK2053 *2054 * // ... but not when comparing both name and race2055 * assertThat(newArrayList(frodo)).usingElementComparatorOnFields("name", "race").contains(sam); // FAIL</code></pre>2056 *2057 * @param fields the fields/properties to compare using element comparators2058 * @return {@code this} assertion object.2059 */2060 @CheckReturnValue2061 public SELF usingElementComparatorOnFields(String... fields) {2062 return usingExtendedByTypesElementComparator(new OnFieldsComparator(comparatorsForElementPropertyOrFieldNames,2063 getComparatorsForElementPropertyOrFieldTypes(),2064 fields));2065 }2066 protected SELF usingComparisonStrategy(ComparisonStrategy comparisonStrategy) {2067 iterables = new Iterables(comparisonStrategy);2068 return myself;2069 }2070 /**2071 * Use field/property by field/property comparison on all fields/properties <b>except</b> the given ones (including inherited2072 * fields/properties) instead of relying on actual type A <code>equals</code> method to compare group elements for2073 * incoming assertion checks. Private fields are included but this can be disabled using2074 * {@link Assertions#setAllowExtractingPrivateFields(boolean)}.2075 * <p>2076 * This can be handy if <code>equals</code> method of the objects to compare does not suit you.2077 * <p>2078 * You can specify a custom comparator per name or type of element field with2079 * {@link #usingComparatorForElementFieldsWithNames(Comparator, String...)}2080 * and {@link #usingComparatorForElementFieldsWithType(Comparator, Class)}.2081 * <p>2082 * Note that the comparison is <b>not</b> recursive, if one of the fields/properties is an Object, it will be compared2083 * to the other field/property using its <code>equals</code> method.2084 * </p>2085 * Example:2086 * <pre><code class='java'> TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT);2087 * TolkienCharacter sam = new TolkienCharacter("Sam", 38, HOBBIT);2088 *2089 * // frodo and sam both are hobbits, so they are equals when comparing only race (i.e. ignoring all other fields)2090 * assertThat(newArrayList(frodo)).usingElementComparatorIgnoringFields("name", "age").contains(sam); // OK2091 *2092 * // ... but not when comparing both name and race2093 * assertThat(newArrayList(frodo)).usingElementComparatorIgnoringFields("age").contains(sam); // FAIL</code></pre>2094 *2095 * @param fields the fields/properties to compare using element comparators2096 * @return {@code this} assertion object.2097 */2098 @CheckReturnValue2099 public SELF usingElementComparatorIgnoringFields(String... fields) {2100 return usingExtendedByTypesElementComparator(new IgnoringFieldsComparator(comparatorsForElementPropertyOrFieldNames,2101 getComparatorsForElementPropertyOrFieldTypes(),2102 fields));2103 }2104 /**2105 * Enable hexadecimal representation of Iterable elements instead of standard representation in error messages.2106 * <p>2107 * It can be useful to better understand what the error was with a more meaningful error message.2108 * <p>2109 * Example2110 * <pre><code class='java'> final List&lt;Byte&gt; bytes = newArrayList((byte) 0x10, (byte) 0x20);</code></pre>2111 *2112 * With standard error message:2113 * <pre><code class='java'> assertThat(bytes).contains((byte) 0x30);2114 *2115 * Expecting:2116 * &lt;[16, 32]&gt;2117 * to contain:2118 * &lt;[48]&gt;2119 * but could not find:2120 * &lt;[48]&gt;</code></pre>2121 *2122 * With Hexadecimal error message:2123 * <pre><code class='java'> assertThat(bytes).inHexadecimal().contains((byte) 0x30);2124 *2125 * Expecting:2126 * &lt;[0x10, 0x20]&gt;2127 * to contain:2128 * &lt;[0x30]&gt;2129 * but could not find:2130 * &lt;[0x30]&gt;</code></pre>2131 *2132 * @return {@code this} assertion object.2133 */2134 @Override2135 @CheckReturnValue2136 public SELF inHexadecimal() {2137 return super.inHexadecimal();2138 }2139 /**2140 * Enable binary representation of Iterable elements instead of standard representation in error messages.2141 * <p>2142 * Example:2143 * <pre><code class='java'> final List&lt;Byte&gt; bytes = newArrayList((byte) 0x10, (byte) 0x20);</code></pre>2144 *2145 * With standard error message:2146 * <pre><code class='java'> assertThat(bytes).contains((byte) 0x30);2147 *2148 * Expecting:2149 * &lt;[16, 32]&gt;2150 * to contain:2151 * &lt;[48]&gt;2152 * but could not find:2153 * &lt;[48]&gt;</code></pre>2154 *2155 * With binary error message:2156 * <pre><code class='java'> assertThat(bytes).inBinary().contains((byte) 0x30);2157 *2158 * Expecting:2159 * &lt;[0b00010000, 0b00100000]&gt;2160 * to contain:2161 * &lt;[0b00110000]&gt;2162 * but could not find:2163 * &lt;[0b00110000]&gt;</code></pre>2164 *2165 * @return {@code this} assertion object.2166 */2167 @Override2168 @CheckReturnValue2169 public SELF inBinary() {2170 return super.inBinary();2171 }2172 /**2173 * Filters the iterable under test keeping only elements having a property or field equal to {@code expectedValue}, the2174 * property/field is specified by {@code propertyOrFieldName} parameter.2175 * <p>2176 * The filter first tries to get the value from a property (named {@code propertyOrFieldName}), if no such property2177 * exists it tries to read the value from a field. Reading private fields is supported by default, this can be2178 * globally disabled by calling {@link Assertions#setAllowExtractingPrivateFields(boolean)2179 * Assertions.setAllowExtractingPrivateFields(false)}.2180 * <p>2181 * When reading <b>nested</b> property/field, if an intermediate value is null the whole nested property/field is2182 * considered to be null, thus reading "address.street.name" value will return null if "street" value is null.2183 * <p>2184 *2185 * As an example, let's check all employees 800 years old (yes, special employees):2186 * <pre><code class='java'> Employee yoda = new Employee(1L, new Name("Yoda"), 800);2187 * Employee obiwan = new Employee(2L, new Name("Obiwan"), 800);2188 * Employee luke = new Employee(3L, new Name("Luke", "Skywalker"), 26);2189 * Employee noname = new Employee(4L, null, 50);2190 *2191 * List&lt;Employee&gt; employees = newArrayList(yoda, luke, obiwan, noname);2192 *2193 * assertThat(employees).filteredOn("age", 800)2194 * .containsOnly(yoda, obiwan);</code></pre>2195 *2196 * Nested properties/fields are supported:2197 * <pre><code class='java'> // Name is bean class with 'first' and 'last' String properties2198 *2199 * // name is null for noname =&gt; it does not match the filter on "name.first"2200 * assertThat(employees).filteredOn("name.first", "Luke")2201 * .containsOnly(luke);2202 *2203 * assertThat(employees).filteredOn("name.last", "Vader")2204 * .isEmpty();</code></pre>2205 * <p>2206 * If you want to filter on null value, use {@link #filteredOnNull(String)} as Java will resolve the call to2207 * {@link #filteredOn(String, FilterOperator)} instead of this method.2208 * <p>2209 * An {@link IntrospectionError} is thrown if the given propertyOrFieldName can't be found in one of the iterable2210 * elements.2211 * <p>2212 * You can chain filters:2213 * <pre><code class='java'> // fellowshipOfTheRing is a list of TolkienCharacter having race and name fields2214 * // 'not' filter is statically imported from Assertions.not2215 *2216 * assertThat(fellowshipOfTheRing).filteredOn("race.name", "Man")2217 * .filteredOn("name", not("Boromir"))2218 * .containsOnly(aragorn);</code></pre>2219 *2220 * If you need more complex filter, use {@link #filteredOn(Predicate)} or {@link #filteredOn(Condition)}.2221 *2222 * @param propertyOrFieldName the name of the property or field to read2223 * @param expectedValue the value to compare element's property or field with2224 * @return a new assertion object with the filtered iterable under test2225 * @throws IllegalArgumentException if the given propertyOrFieldName is {@code null} or empty.2226 * @throws IntrospectionError if the given propertyOrFieldName can't be found in one of the iterable elements.2227 */2228 @CheckReturnValue2229 public SELF filteredOn(String propertyOrFieldName, Object expectedValue) {2230 Filters<? extends ELEMENT> filter = filter((Iterable<? extends ELEMENT>) actual);2231 Iterable<? extends ELEMENT> filteredIterable = filter.with(propertyOrFieldName, expectedValue).get();2232 return newAbstractIterableAssert(filteredIterable).withAssertionState(myself);2233 }2234 /**2235 * Filters the iterable under test keeping only elements whose property or field specified by2236 * {@code propertyOrFieldName} is null.2237 * <p>2238 * The filter first tries to get the value from a property (named {@code propertyOrFieldName}), if no such property2239 * exists it tries to read the value from a field. Reading private fields is supported by default, this can be2240 * globally disabled by calling {@link Assertions#setAllowExtractingPrivateFields(boolean)2241 * Assertions.setAllowExtractingPrivateFields(false)}.2242 * <p>2243 * When reading <b>nested</b> property/field, if an intermediate value is null the whole nested property/field is2244 * considered to be null, thus reading "address.street.name" value will return null if "street" value is null.2245 * <p>2246 * As an example, let's check all employees 800 years old (yes, special employees):2247 * <pre><code class='java'> Employee yoda = new Employee(1L, new Name("Yoda"), 800);2248 * Employee obiwan = new Employee(2L, new Name("Obiwan"), 800);2249 * Employee luke = new Employee(3L, new Name("Luke", "Skywalker"), 26);2250 * Employee noname = new Employee(4L, null, 50);2251 *2252 * List&lt;Employee&gt; employees = newArrayList(yoda, luke, obiwan, noname);2253 *2254 * assertThat(employees).filteredOnNull("name")2255 * .containsOnly(noname);</code></pre>2256 *2257 * Nested properties/fields are supported:2258 * <pre><code class='java'> // Name is bean class with 'first' and 'last' String properties2259 *2260 * assertThat(employees).filteredOnNull("name.last")2261 * .containsOnly(yoda, obiwan, noname);</code></pre>2262 *2263 * An {@link IntrospectionError} is thrown if the given propertyOrFieldName can't be found in one of the iterable2264 * elements.2265 * <p>2266 * If you need more complex filter, use {@link #filteredOn(Predicate)} or {@link #filteredOn(Condition)}.2267 *2268 * @param propertyOrFieldName the name of the property or field to read2269 * @return a new assertion object with the filtered iterable under test2270 * @throws IntrospectionError if the given propertyOrFieldName can't be found in one of the iterable elements.2271 */2272 @CheckReturnValue2273 public SELF filteredOnNull(String propertyOrFieldName) {2274 // can't call filteredOn(String propertyOrFieldName, null) as it does not work with soft assertions proxying2275 // mechanism, it would lead to double proxying which is not handle properly (improvements needed in our proxy mechanism)2276 Filters<? extends ELEMENT> filter = filter((Iterable<? extends ELEMENT>) actual);2277 Iterable<? extends ELEMENT> filteredIterable = filter.with(propertyOrFieldName, null).get();2278 return newAbstractIterableAssert(filteredIterable).withAssertionState(myself);2279 }2280 /**2281 * Filters the iterable under test keeping only elements having a property or field matching the filter expressed with2282 * the {@link FilterOperator}, the property/field is specified by {@code propertyOrFieldName} parameter.2283 * <p>2284 * The existing filters are :2285 * <ul>2286 * <li> {@link Assertions#not(Object) not(Object)}</li>2287 * <li> {@link Assertions#in(Object...) in(Object...)}</li>2288 * <li> {@link Assertions#notIn(Object...) notIn(Object...)}</li>2289 * </ul>2290 * <p>2291 * Whatever filter is applied, it first tries to get the value from a property (named {@code propertyOrFieldName}), if2292 * no such property exists it tries to read the value from a field. Reading private fields is supported by default,2293 * this can be globally disabled by calling {@link Assertions#setAllowExtractingPrivateFields(boolean)2294 * Assertions.setAllowExtractingPrivateFields(false)}.2295 * <p>2296 * When reading <b>nested</b> property/field, if an intermediate value is null the whole nested property/field is2297 * considered to be null, thus reading "address.street.name" value will return null if "street" value is null.2298 * <p>2299 *2300 * As an example, let's check stuff on some special employees :2301 * <pre><code class='java'> Employee yoda = new Employee(1L, new Name("Yoda"), 800);2302 * Employee obiwan = new Employee(2L, new Name("Obiwan"), 800);2303 * Employee luke = new Employee(3L, new Name("Luke", "Skywalker"), 26);2304 *2305 * List&lt;Employee&gt; employees = newArrayList(yoda, luke, obiwan, noname);2306 *2307 * // 'not' filter is statically imported from Assertions.not2308 * assertThat(employees).filteredOn("age", not(800))2309 * .containsOnly(luke);2310 *2311 * // 'in' filter is statically imported from Assertions.in2312 * // Name is bean class with 'first' and 'last' String properties2313 * assertThat(employees).filteredOn("name.first", in("Yoda", "Luke"))2314 * .containsOnly(yoda, luke);2315 *2316 * // 'notIn' filter is statically imported from Assertions.notIn2317 * assertThat(employees).filteredOn("name.first", notIn("Yoda", "Luke"))2318 * .containsOnly(obiwan);</code></pre>2319 *2320 * An {@link IntrospectionError} is thrown if the given propertyOrFieldName can't be found in one of the iterable2321 * elements.2322 * <p>2323 * Note that combining filter operators is not supported, thus the following code is not correct:2324 * <pre><code class='java'> // Combining filter operators like not(in(800)) is NOT supported2325 * // -&gt; throws UnsupportedOperationException2326 * assertThat(employees).filteredOn("age", not(in(800)))2327 * .contains(luke);</code></pre>2328 * <p>2329 * You can chain filters:2330 * <pre><code class='java'> // fellowshipOfTheRing is a list of TolkienCharacter having race and name fields2331 * // 'not' filter is statically imported from Assertions.not2332 *2333 * assertThat(fellowshipOfTheRing).filteredOn("race.name", "Man")2334 * .filteredOn("name", not("Boromir"))2335 * .containsOnly(aragorn);</code></pre>2336 *2337 * If you need more complex filter, use {@link #filteredOn(Predicate)} or {@link #filteredOn(Condition)}.2338 *2339 * @param propertyOrFieldName the name of the property or field to read2340 * @param filterOperator the filter operator to apply2341 * @return a new assertion object with the filtered iterable under test2342 * @throws IllegalArgumentException if the given propertyOrFieldName is {@code null} or empty.2343 */2344 @CheckReturnValue2345 public SELF filteredOn(String propertyOrFieldName, FilterOperator<?> filterOperator) {2346 checkNotNull(filterOperator);2347 Filters<? extends ELEMENT> filter = filter((Iterable<? extends ELEMENT>) actual).with(propertyOrFieldName);2348 filterOperator.applyOn(filter);2349 return newAbstractIterableAssert(filter.get()).withAssertionState(myself);2350 }2351 /**2352 * Filters the iterable under test keeping only elements matching the given {@link Condition}.2353 * <p>2354 * If you prefer {@link Predicate} over {@link Condition}, use {@link #filteredOn(Predicate)}.2355 * <p>2356 * Example : check old employees whose age &gt; 100:2357 * <pre><code class='java'> Employee yoda = new Employee(1L, new Name("Yoda"), 800);2358 * Employee obiwan = new Employee(2L, new Name("Obiwan"), 800);2359 * Employee luke = new Employee(3L, new Name("Luke", "Skywalker"), 26);2360 * Employee noname = new Employee(4L, null, 50);2361 *2362 * List&lt;Employee&gt; employees = newArrayList(yoda, luke, obiwan, noname);2363 *2364 * // old employee condition, "old employees" describes the condition in error message2365 * // you just have to implement 'matches' method2366 * Condition&lt;Employee&gt; oldEmployees = new Condition&lt;Employee&gt;("old employees") {2367 * {@literal @}Override2368 * public boolean matches(Employee employee) {2369 * return employee.getAge() &gt; 100;2370 * }2371 * };2372 * }2373 * assertThat(employees).filteredOn(oldEmployees)2374 * .containsOnly(yoda, obiwan);</code></pre>2375 *2376 * You can combine {@link Condition} with condition operator like {@link Not}:2377 * <pre><code class='java'> // 'not' filter is statically imported from Assertions.not2378 * assertThat(employees).filteredOn(not(oldEmployees))2379 * .contains(luke, noname);</code></pre>2380 *2381 * @param condition the filter condition / predicate2382 * @return a new assertion object with the filtered iterable under test2383 * @throws IllegalArgumentException if the given condition is {@code null}.2384 */2385 @CheckReturnValue2386 public SELF filteredOn(Condition<? super ELEMENT> condition) {2387 Filters<? extends ELEMENT> filter = filter((Iterable<? extends ELEMENT>) actual);2388 Iterable<? extends ELEMENT> filteredIterable = filter.being(condition).get();2389 return newAbstractIterableAssert(filteredIterable).withAssertionState(myself);2390 }2391 /**2392 * Filters the iterable under test keeping only elements for which the result of the {@code function} is equal to {@code expectedValue}.2393 * <p>2394 * It allows to filter elements more safely than by using {@link #filteredOn(String, Object)} as it doesn't utilize introspection.2395 * <p>2396 * As an example, let's check all employees 800 years old (yes, special employees):2397 * <pre><code class='java'> Employee yoda = new Employee(1L, new Name("Yoda"), 800);2398 * Employee obiwan = new Employee(2L, new Name("Obiwan"), 800);2399 * Employee luke = new Employee(3L, new Name("Luke", "Skywalker"), 26);2400 * Employee noname = new Employee(4L, null, 50);2401 *2402 * List&lt;Employee&gt; employees = newArrayList(yoda, luke, obiwan, noname);2403 *2404 * assertThat(employees).filteredOn(Employee::getAge, 800)2405 * .containsOnly(yoda, obiwan);2406 *2407 * assertThat(employees).filteredOn(e -&gt; e.getName(), null)2408 * .containsOnly(noname);</code></pre>2409 *2410 * If you need more complex filter, use {@link #filteredOn(Predicate)} or {@link #filteredOn(Condition)}.2411 *2412 * @param <T> result type of the filter function2413 * @param function the filter function2414 * @param expectedValue the expected value of the filter function2415 * @return a new assertion object with the filtered iterable under test2416 * @throws IllegalArgumentException if the given function is {@code null}.2417 * @since 3.17.02418 */2419 @CheckReturnValue2420 public <T> SELF filteredOn(Function<? super ELEMENT, T> function, T expectedValue) {2421 checkArgument(function != null, "The filter function should not be null");2422 // call internalFilteredOn to avoid double proxying in soft assertions2423 return internalFilteredOn(element -> java.util.Objects.equals(function.apply(element), expectedValue));2424 }2425 /**2426 * Filters the iterable under test keeping only elements matching the given assertions specified with a {@link Consumer}.2427 * <p>2428 * Example : check young hobbits whose age &lt; 34:2429 *2430 * <pre><code class='java'> TolkienCharacter pippin = new TolkienCharacter("Pippin", 28, HOBBIT);2431 * TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT);2432 * TolkienCharacter merry = new TolkienCharacter("Merry", 36, HOBBIT);2433 * TolkienCharacter sam = new TolkienCharacter("Sam", 38, HOBBIT);2434 *2435 * List&lt;TolkienCharacter&gt; hobbits = list(frodo, sam, merry, pippin);2436 *2437 * assertThat(hobbits).filteredOnAssertions(hobbit -&gt; assertThat(hobbit.age).isLessThan(34))2438 * .containsOnly(frodo, pippin);</code></pre>2439 *2440 * @param elementAssertions containing AssertJ assertions to filter on2441 * @return a new assertion object with the filtered iterable under test2442 * @throws IllegalArgumentException if the given predicate is {@code null}.2443 * @since 3.11.02444 */2445 public SELF filteredOnAssertions(Consumer<? super ELEMENT> elementAssertions) {2446 checkArgument(elementAssertions != null, "The element assertions should not be null");2447 List<? extends ELEMENT> filteredIterable = stream(actual.spliterator(), false).filter(byPassingAssertions(elementAssertions))2448 .collect(toList());2449 return newAbstractIterableAssert(filteredIterable).withAssertionState(myself);2450 }2451 // navigable assertions2452 /**2453 * Navigate and allow to perform assertions on the first element of the {@link Iterable} under test.2454 * <p>2455 * By default available assertions after {@code first()} are {@code Object} assertions, it is possible though to2456 * get more specific assertions if you create {@code IterableAssert} with either:2457 * <ul>2458 * <li>the element assert class, see: {@link Assertions#assertThat(Iterable, Class) assertThat(Iterable, element assert class)}</li>2459 * <li>an assert factory used that knows how to create elements assertion, see: {@link Assertions#assertThat(Iterable, AssertFactory) assertThat(Iterable, element assert factory)}</li>2460 * </ul>2461 * <p>2462 * Example: default {@code Object} assertions2463 * <pre><code class='java'> // default iterable assert =&gt; element assert is ObjectAssert2464 * Iterable&lt;TolkienCharacter&gt; hobbits = newArrayList(frodo, sam, pippin);2465 *2466 * // assertion succeeds, only Object assertions are available after first()2467 * assertThat(hobbits).first()2468 * .isEqualTo(frodo);2469 *2470 * // assertion fails2471 * assertThat(hobbits).first()2472 * .isEqualTo(pippin);</code></pre>2473 * <p>2474 * If you have created the Iterable assertion using an {@link AssertFactory} or the element assert class,2475 * you will be able to chain {@code first()} with more specific typed assertion.2476 * <p>2477 * Example: use of {@code String} assertions after {@code first()}2478 * <pre><code class='java'> Iterable&lt;String&gt; hobbits = newArrayList("Frodo", "Sam", "Pippin");2479 *2480 * // assertion succeeds2481 * // String assertions are available after first()2482 * assertThat(hobbits, StringAssert.class).first()2483 * .startsWith("Fro")2484 * .endsWith("do");2485 * // assertion fails2486 * assertThat(hobbits, StringAssert.class).first()2487 * .startsWith("Pip");</code></pre>2488 *2489 * @return the assertion on the first element2490 * @throws AssertionError if the actual {@link Iterable} is empty.2491 * @since 2.5.0 / 3.5.02492 * @see #first(InstanceOfAssertFactory)2493 */2494 @CheckReturnValue2495 public ELEMENT_ASSERT first() {2496 return internalFirst();2497 }2498 /**2499 * Navigate and allow to perform assertions on the first element of the {@link Iterable} under test.2500 * <p>2501 * The {@code assertFactory} parameter allows to specify an {@link InstanceOfAssertFactory}, which is used to get the2502 * assertions narrowed to the factory type.2503 * <p>2504 * Example: use of {@code String} assertions after {@code first(as(InstanceOfAssertFactories.STRING)}2505 * <pre><code class='java'> Iterable&lt;String&gt; hobbits = newArrayList("Frodo", "Sam", "Pippin");2506 *2507 * // assertion succeeds2508 * assertThat(hobbits).first(as(InstanceOfAssertFactories.STRING))2509 * .startsWith("Fro")2510 * .endsWith("do");2511 * // assertion fails2512 * assertThat(hobbits).first(as(InstanceOfAssertFactories.STRING))2513 * .startsWith("Pip");2514 * // assertion fails because of wrong factory type2515 * assertThat(hobbits).first(as(InstanceOfAssertFactories.INTEGER))2516 * .isZero();</code></pre>2517 *2518 * @param <ASSERT> the type of the resulting {@code Assert}2519 * @param assertFactory the factory which verifies the type and creates the new {@code Assert}2520 * @return a new narrowed {@link Assert} instance for assertions chaining on the first element2521 * @throws AssertionError if the actual {@link Iterable} is empty.2522 * @throws NullPointerException if the given factory is {@code null}2523 * @since 3.14.02524 */2525 @CheckReturnValue2526 public <ASSERT extends AbstractAssert<?, ?>> ASSERT first(InstanceOfAssertFactory<?, ASSERT> assertFactory) {2527 return internalFirst().asInstanceOf(assertFactory);2528 }2529 private ELEMENT_ASSERT internalFirst() {2530 isNotEmpty();2531 return toAssert(actual.iterator().next(), navigationDescription("check first element"));2532 }2533 /**2534 * Navigate and allow to perform assertions on the last element of the {@link Iterable} under test.2535 * <p>2536 * By default available assertions after {@code last()} are {@code Object} assertions, it is possible though to2537 * get more specific assertions if you create {@code IterableAssert} with either:2538 * <ul>2539 * <li>the element assert class, see: {@link Assertions#assertThat(Iterable, Class) assertThat(Iterable, element assert class)}</li>2540 * <li>an assert factory used that knows how to create elements assertion, see: {@link Assertions#assertThat(Iterable, AssertFactory) assertThat(Iterable, element assert factory)}</li>2541 * </ul>2542 * <p>2543 * Example: default {@code Object} assertions2544 * <pre><code class='java'> // default iterable assert =&gt; element assert is ObjectAssert2545 * Iterable&lt;TolkienCharacter&gt; hobbits = newArrayList(frodo, sam, pippin);2546 *2547 * // assertion succeeds, only Object assertions are available after last()2548 * assertThat(hobbits).last()2549 * .isEqualTo(pippin);2550 *2551 * // assertion fails2552 * assertThat(hobbits).last()2553 * .isEqualTo(frodo);</code></pre>2554 * <p>2555 * If you have created the Iterable assertion using an {@link AssertFactory} or the element assert class,2556 * you will be able to chain {@code last()} with more specific typed assertion.2557 * <p>2558 * Example: use of {@code String} assertions after {@code last()}2559 * <pre><code class='java'> Iterable&lt;String&gt; hobbits = newArrayList("Frodo", "Sam", "Pippin");2560 *2561 * // assertion succeeds2562 * // String assertions are available after last()2563 * assertThat(hobbits, StringAssert.class).last()2564 * .startsWith("Pi")2565 * .endsWith("in");2566 * // assertion fails2567 * assertThat(hobbits, StringAssert.class).last()2568 * .startsWith("Fro");</code></pre>2569 *2570 * @return the assertion on the last element2571 * @throws AssertionError if the actual {@link Iterable} is empty.2572 * @since 2.5.0 / 3.5.02573 * @see #last(InstanceOfAssertFactory)2574 */2575 @CheckReturnValue2576 public ELEMENT_ASSERT last() {2577 return internalLast();2578 }2579 /**2580 * Navigate and allow to perform assertions on the last element of the {@link Iterable} under test.2581 * <p>2582 * The {@code assertFactory} parameter allows to specify an {@link InstanceOfAssertFactory}, which is used to get the2583 * assertions narrowed to the factory type.2584 * <p>2585 * Example: use of {@code String} assertions after {@code last(as(InstanceOfAssertFactories.STRING)}2586 * <pre><code class='java'> Iterable&lt;String&gt; hobbits = newArrayList("Frodo", "Sam", "Pippin");2587 *2588 * // assertion succeeds2589 * assertThat(hobbits).last(as(InstanceOfAssertFactories.STRING))2590 * .startsWith("Pip")2591 * .endsWith("pin");2592 * // assertion fails2593 * assertThat(hobbits).last(as(InstanceOfAssertFactories.STRING))2594 * .startsWith("Fro");2595 * // assertion fails because of wrong factory type2596 * assertThat(hobbits).last(as(InstanceOfAssertFactories.INTEGER))2597 * .isZero();</code></pre>2598 *2599 * @param <ASSERT> the type of the resulting {@code Assert}2600 * @param assertFactory the factory which verifies the type and creates the new {@code Assert}2601 * @return a new narrowed {@link Assert} instance for assertions chaining on the last element2602 * @throws AssertionError if the actual {@link Iterable} is empty.2603 * @throws NullPointerException if the given factory is {@code null}2604 * @since 3.14.02605 */2606 @CheckReturnValue2607 public <ASSERT extends AbstractAssert<?, ?>> ASSERT last(InstanceOfAssertFactory<?, ASSERT> assertFactory) {2608 return internalLast().asInstanceOf(assertFactory);2609 }2610 private ELEMENT_ASSERT internalLast() {2611 isNotEmpty();2612 return toAssert(lastElement(), navigationDescription("check last element"));2613 }2614 private ELEMENT lastElement() {2615 if (actual instanceof List) {2616 @SuppressWarnings("unchecked")2617 List<? extends ELEMENT> list = (List<? extends ELEMENT>) actual;2618 return list.get(list.size() - 1);2619 }2620 Iterator<? extends ELEMENT> actualIterator = actual.iterator();2621 ELEMENT last = actualIterator.next();2622 while (actualIterator.hasNext()) {2623 last = actualIterator.next();2624 }2625 return last;2626 }2627 /**2628 * Navigate and allow to perform assertions on the chosen element of the {@link Iterable} under test.2629 * <p>2630 * By default available assertions after {@code element(index)} are {@code Object} assertions, it is possible though to2631 * get more specific assertions if you create {@code IterableAssert} with either:2632 * <ul>2633 * <li>the element assert class, see: {@link Assertions#assertThat(Iterable, Class) assertThat(Iterable, element assert class)}</li>2634 * <li>an assert factory used that knows how to create elements assertion, see: {@link Assertions#assertThat(Iterable, AssertFactory) assertThat(Iterable, element assert factory)}</li>2635 * </ul>2636 * <p>2637 * Example: default {@code Object} assertions2638 * <pre><code class='java'> // default iterable assert =&gt; element assert is ObjectAssert2639 * Iterable&lt;TolkienCharacter&gt; hobbits = newArrayList(frodo, sam, pippin);2640 *2641 * // assertion succeeds, only Object assertions are available after element(index)2642 * assertThat(hobbits).element(1)2643 * .isEqualTo(sam);2644 *2645 * // assertion fails2646 * assertThat(hobbits).element(1)2647 * .isEqualTo(pippin);</code></pre>2648 * <p>2649 * If you have created the Iterable assertion using an {@link AssertFactory} or the element assert class,2650 * you will be able to chain {@code element(index)} with more specific typed assertion.2651 * <p>2652 * Example: use of {@code String} assertions after {@code element(index)}2653 * <pre><code class='java'> Iterable&lt;String&gt; hobbits = newArrayList("Frodo", "Sam", "Pippin");2654 *2655 * // assertion succeeds2656 * // String assertions are available after element(index)2657 * assertThat(hobbits, StringAssert.class).element(1)2658 * .startsWith("Sa")2659 * .endsWith("am");2660 * // assertion fails2661 * assertThat(hobbits, StringAssert.class).element(1)2662 * .startsWith("Fro");</code></pre>2663 *2664 * @param index the element's index2665 * @return the assertion on the given element2666 * @throws AssertionError if the given index is out of bound.2667 * @since 2.5.0 / 3.5.02668 * @see #element(int, InstanceOfAssertFactory)2669 */2670 @CheckReturnValue2671 public ELEMENT_ASSERT element(int index) {2672 return internalElement(index);2673 }2674 /**2675 * Navigate and allow to perform assertions on the chosen element of the {@link Iterable} under test.2676 * <p>2677 * The {@code assertFactory} parameter allows to specify an {@link InstanceOfAssertFactory}, which is used to get the2678 * assertions narrowed to the factory type.2679 * <p>2680 * Example: use of {@code String} assertions after {@code element(index, as(InstanceOfAssertFactories.STRING)}2681 * <pre><code class='java'> Iterable&lt;String&gt; hobbits = newArrayList("Frodo", "Sam", "Pippin");2682 *2683 * // assertion succeeds2684 * assertThat(hobbits).element(1, as(InstanceOfAssertFactories.STRING))2685 * .startsWith("Sa")2686 * .endsWith("am");2687 * // assertion fails2688 * assertThat(hobbits).element(1, as(InstanceOfAssertFactories.STRING))2689 * .startsWith("Fro");2690 * // assertion fails because of wrong factory type2691 * assertThat(hobbits).element(1, as(InstanceOfAssertFactories.INTEGER))2692 * .isZero();</code></pre>2693 *2694 * @param <ASSERT> the type of the resulting {@code Assert}2695 * @param index the element's index2696 * @param assertFactory the factory which verifies the type and creates the new {@code Assert}2697 * @return a new narrowed {@link Assert} instance for assertions chaining on the element at the given index2698 * @throws AssertionError if the given index is out of bound.2699 * @throws NullPointerException if the given factory is {@code null}2700 * @since 3.14.02701 */2702 @CheckReturnValue2703 public <ASSERT extends AbstractAssert<?, ?>> ASSERT element(int index, InstanceOfAssertFactory<?, ASSERT> assertFactory) {2704 return internalElement(index).asInstanceOf(assertFactory);2705 }2706 private ELEMENT_ASSERT internalElement(int index) {2707 isNotEmpty();2708 assertThat(index).describedAs(navigationDescription("check index validity"))2709 .isBetween(0, IterableUtil.sizeOf(actual) - 1);2710 ELEMENT elementAtIndex;2711 if (actual instanceof List) {2712 @SuppressWarnings("unchecked")2713 List<? extends ELEMENT> list = (List<? extends ELEMENT>) actual;2714 elementAtIndex = list.get(index);2715 } else {2716 Iterator<? extends ELEMENT> actualIterator = actual.iterator();2717 for (int i = 0; i < index; i++) {2718 actualIterator.next();2719 }2720 elementAtIndex = actualIterator.next();2721 }2722 return toAssert(elementAtIndex, navigationDescription("element at index " + index));2723 }2724 /**2725 * Verifies that the {@link Iterable} under test contains a single element and allows to perform assertions that element.2726 * <p>2727 * This is a shorthand for <code>hasSize(1).first()</code>.2728 * <p>2729 * By default available assertions after {@code singleElement()} are {@code Object} assertions, it is possible though to2730 * get more specific assertions if you create {@code IterableAssert} with either:2731 * <ul>2732 * <li>the element assert class, see: {@link Assertions#assertThat(Iterable, Class) assertThat(Iterable, element assert class)}</li>2733 * <li>an assert factory used that knows how to create elements assertion, see: {@link Assertions#assertThat(Iterable, AssertFactory) assertThat(Iterable, element assert factory)}</li>2734 * <li>the general <code>assertThat(Iterable)</code> and narrow down the single element with an assert factory, see: {@link #singleElement(InstanceOfAssertFactory) singleElement(element assert factory)}</li>2735 * </ul>2736 * <p>2737 * Example: default {@code Object} assertions2738 * <pre><code class='java'> List&lt;String&gt; babySimpsons = list("Maggie");2739 *2740 * // assertion succeeds, only Object assertions are available after singleElement()2741 * assertThat(babySimpsons).singleElement()2742 * .isEqualTo("Maggie");2743 *2744 * // assertion fails2745 * assertThat(babySimpsons).singleElement()2746 * .isEqualTo("Homer");2747 *2748 * // assertion fails because list contains no elements2749 * assertThat(emptyList()).singleElement();2750 *2751 *2752 * // assertion fails because list contains more than one element2753 * List&lt;String&gt; simpsons = list("Homer", "Marge", "Lisa", "Bart", "Maggie");2754 * assertThat(simpsons).singleElement();</code></pre>2755 * <p>2756 * If you have created the Iterable assertion using an {@link AssertFactory} or the element assert class,2757 * you will be able to chain {@code singleElement()} with more specific typed assertion.2758 * <p>2759 * Example: use of {@code String} assertions after {@code singleElement()}2760 * <pre><code class='java'> List&lt;String&gt; babySimpsons = list("Maggie");2761 *2762 * // assertion succeeds2763 * // String assertions are available after singleElement()2764 * assertThat(babySimpsons, StringAssert.class).singleElement()2765 * .startsWith("Mag");2766 *2767 * // InstanceOfAssertFactories.STRING is an AssertFactory for String assertions2768 * assertThat(babySimpsons, InstanceOfAssertFactories.STRING).singleElement()2769 * .startsWith("Mag");2770 * // better readability with import static InstanceOfAssertFactories.STRING and Assertions.as2771 * assertThat(babySimpsons, as(STRING)).singleElement()2772 * .startsWith("Mag");2773 *2774 * // assertions fail2775 * assertThat(babySimpsons, StringAssert.class).singleElement()2776 * .startsWith("Lis");2777 * // failure as the single element is not an int/Integer2778 * assertThat(babySimpsons, IntegerAssert.class).singleElement()2779 * .startsWith("Lis");</code></pre>2780 *2781 * @return the assertion on the first element2782 * @throws AssertionError if the actual {@link Iterable} does not contain exactly one element.2783 * @since 3.17.02784 * @see #singleElement(InstanceOfAssertFactory)2785 */2786 @CheckReturnValue2787 public ELEMENT_ASSERT singleElement() {2788 return internalSingleElement();2789 }2790 /**2791 * Verifies that the {@link Iterable} under test contains a single element and allows to perform assertions on that element.<br>2792 * The assertions are strongly typed according to the given {@link AssertFactory} parameter.2793 * <p>2794 * This is a shorthand for <code>hasSize(1).first(assertFactory)</code>.2795 * <p>2796 * Example: use of {@code String} assertions after {@code singleElement(as(STRING)}2797 * <pre><code class='java'> import static org.assertj.core.api.InstanceOfAssertFactories.STRING;2798 * import static org.assertj.core.api.InstanceOfAssertFactories.INTEGER;2799 * import static org.assertj.core.api.Assertions.as; // syntactic sugar2800 *2801 * List&lt;String&gt; babySimpsons = list("Maggie");2802 *2803 * // assertion succeeds2804 * assertThat(babySimpsons).singleElement(as(STRING))2805 * .startsWith("Mag");2806 *2807 * // assertion fails2808 * assertThat(babySimpsons).singleElement(as(STRING))2809 * .startsWith("Lis");2810 *2811 * // assertion fails because of wrong factory type2812 * assertThat(babySimpsons).singleElement(as(INTEGER))2813 * .isZero();2814 *2815 * // assertion fails because list contains no elements2816 * assertThat(emptyList()).singleElement(as(STRING));2817 *2818 * // assertion fails because list contains more than one element2819 * List&lt;String&gt; simpsons = list("Homer", "Marge", "Lisa", "Bart", "Maggie");2820 * assertThat(simpsons).singleElement(as(STRING));</code></pre>2821 *2822 * @param <ASSERT> the type of the resulting {@code Assert}2823 * @param assertFactory the factory which verifies the type and creates the new {@code Assert}2824 * @return a new narrowed {@link Assert} instance for assertions chaining on the single element2825 * @throws AssertionError if the actual {@link Iterable} does not contain exactly one element.2826 * @throws NullPointerException if the given factory is {@code null}.2827 * @since 3.17.02828 */2829 @CheckReturnValue2830 public <ASSERT extends AbstractAssert<?, ?>> ASSERT singleElement(InstanceOfAssertFactory<?, ASSERT> assertFactory) {2831 return internalSingleElement().asInstanceOf(assertFactory);2832 }2833 private ELEMENT_ASSERT internalSingleElement() {2834 iterables.assertHasSize(info, actual, 1);2835 return internalFirst();2836 }2837 protected abstract ELEMENT_ASSERT toAssert(ELEMENT value, String description);2838 protected String navigationDescription(String propertyName) {2839 String text = descriptionText();2840 if (Strings.isNullOrEmpty(text)) {2841 text = removeAssert(this.getClass().getSimpleName());2842 }2843 return text + " " + propertyName;2844 }...

Full Screen

Full Screen

singleElement

Using AI Code Generation

copy

Full Screen

1import org.assertj.core.api.AbstractObjectArrayAssert;2import org.assertj.core.api.Assertions;3import org.assertj.core.api.ObjectArrayAssert;4public class 1 {5 public static void main(String[] args) {6 ObjectArrayAssert<String> objectArrayAssert = Assertions.assertThat(new String[]{"a", "b", "c"});7 AbstractObjectArrayAssert<?, String> stringAbstractObjectArrayAssert = objectArrayAssert.singleElement();8 System.out.println(stringAbstractObjectArrayAssert);9 }10}

Full Screen

Full Screen

singleElement

Using AI Code Generation

copy

Full Screen

1import org.assertj.core.api.*;2public class SingleElement {3 public static void main(String[] args) {4 Integer[] array = { 1, 2, 3 };5 AbstractObjectArrayAssert<?, Integer[]> assertion = Assertions.assertThat(array);6 assertion.singleElement().isEqualTo(3);7 }8}

Full Screen

Full Screen

singleElement

Using AI Code Generation

copy

Full Screen

1import static org.assertj.core.api.Assertions.*;2import org.assertj.core.api.AbstractObjectArrayAssert;3public class SingleElement {4 public static void main(String[] args) {5 String[] array = {"Java"};6 AbstractObjectArrayAssert<?, ?> assertObj = assertThat(array);7 assertObj.singleElement();8 }9}

Full Screen

Full Screen

singleElement

Using AI Code Generation

copy

Full Screen

1import static org.assertj.core.api.Assertions.*;2import org.assertj.core.api.AbstractObjectArrayAssert;3public class SingleElement {4 public static void main(String args[]) {5 Object[] objArray = new Object[] { "Geeks", "for", "Geeks" };6 Object[] objArray1 = new Object[] { "Geeks" };7 Object[] objArray2 = new Object[] { "Geeks", "for", "Geeks", "Geeks" };8 Object[] objArray3 = new Object[] { "Geeks", "Geeks", "Geeks" };9 AbstractObjectArrayAssert<?, ?> abstractObjectArrayAssert = assertThat(objArray);10 abstractObjectArrayAssert.singleElement();11 System.out.println("The array contains only one element");12 abstractObjectArrayAssert = assertThat(objArray1);13 abstractObjectArrayAssert.singleElement();14 System.out.println("The array contains only one element");15 abstractObjectArrayAssert = assertThat(objArray2);16 abstractObjectArrayAssert.singleElement();17 System.out.println("The array contains only one element");18 abstractObjectArrayAssert = assertThat(objArray3);19 abstractObjectArrayAssert.singleElement();20 System.out.println("The array contains only one element");21 }22}23 at SingleElement.main(SingleElement.java:35)

Full Screen

Full Screen

singleElement

Using AI Code Generation

copy

Full Screen

1public class SingleElement {2 public static void main(String[] args) {3 Object[] arr = {"one", "two", "three"};4 Assertions.assertThat(arr).singleElement().isEqualTo("one");5 }6}7public AbstractObjectArrayAssert<T> singleElement() 8public AbstractObjectArrayAssert<T> singleElement(Condition<? super T> condition) 9public AbstractObjectArrayAssert<T> singleElement(Condition<? super T> condition, String conditionDescription)10public class SingleElement {11 public static void main(String[] args) {12 Object[] arr = {"one", "two", "three"};13 Assertions.assertThat(arr).singleElement();14 }15}16public class SingleElement {17 public static void main(String[] args) {18 Object[] arr = {"one", "two", "three"};19 Assertions.assertThat(arr).singleElement().isEqualTo("one");20 }21}

Full Screen

Full Screen

singleElement

Using AI Code Generation

copy

Full Screen

1import org.assertj.core.api.*;2import org.assertj.core.api.Assertions.*;3import org.assertj.core.api.AbstractObjectArrayAssert;4import org.assertj.core.api.AbstractObjectArrayAssert.*;5import org.assertj.core.api.AbstractAssert.*;6import org.assertj.core.api.AbstractAssert;7import org.assertj.core.api.AbstractAssert.*;8public class 1 {9 public static void main(String[] args) {10 Object[] obj = new Object[] { "1", "2", "3", "4" };11 AbstractObjectArrayAssert<?, ?> objAssert = Assertions.assertThat(obj);12 objAssert.singleElement();13 }14}15at org.assertj.core.api.AbstractObjectArrayAssert.singleElement(AbstractObjectArrayAssert.java:95)16at 1.main(1.java:13)

Full Screen

Full Screen

singleElement

Using AI Code Generation

copy

Full Screen

1public class SingleElement {2 public static void main(String[] args) {3 String[] array = {"one", "two"};4 Object[] result = Assertions.assertThat(array).singleElement().asList().toArray();5 System.out.println(result[0]);6 }7}

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Assertj automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used method in AbstractObjectArrayAssert

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful