How to use usingExtendedByTypesElementComparator method of org.assertj.core.api.AbstractIterableAssert class

Best Assertj code snippet using org.assertj.core.api.AbstractIterableAssert.usingExtendedByTypesElementComparator

Source:AbstractIterableAssert.java Github

copy

Full Screen

...562 objects = new Objects(new IterableElementComparisonStrategy<>(elementComparator));563 return myself;564 }565 @CheckReturnValue566 private SELF usingExtendedByTypesElementComparator(Comparator<Object> elementComparator) {567 return usingElementComparator(new ExtendedByTypesComparator(elementComparator, comparatorsByType));568 }569 /**570 * {@inheritDoc}571 */572 @Override573 @CheckReturnValue574 public SELF usingDefaultElementComparator() {575 usingDefaultComparator();576 this.iterables = Iterables.instance();577 return myself;578 }579 /**580 * Verifies that the actual {@link Iterable} contains at least one of the given values.581 * <p>582 * Example :583 * <pre><code class='java'> Iterable&lt;String&gt; abc = Arrays.asList("a", "b", "c");584 *585 * // assertions will pass586 * assertThat(abc).containsAnyOf("b")587 * .containsAnyOf("b", "c")588 * .containsAnyOf("a", "b", "c")589 * .containsAnyOf("a", "b", "c", "d")590 * .containsAnyOf("e", "f", "g", "b");591 *592 * // assertions will fail593 * assertThat(abc).containsAnyOf("d");594 * assertThat(abc).containsAnyOf("d", "e", "f", "g");</code></pre>595 *596 * @param values the values whose at least one which is expected to be in the {@code Iterable} under test.597 * @return {@code this} assertion object.598 * @throws NullPointerException if the array of values is {@code null}.599 * @throws IllegalArgumentException if the array of values is empty and the {@code Iterable} under test is not empty.600 * @throws AssertionError if the {@code Iterable} under test is {@code null}.601 * @throws AssertionError if the {@code Iterable} under test does not contain any of the given {@code values}.602 * @since 2.9.0 / 3.9.0603 */604 @Override605 public SELF containsAnyOf(@SuppressWarnings("unchecked") ELEMENT... values) {606 iterables.assertContainsAnyOf(info, actual, values);607 return myself;608 }609 /**610 * Verifies that the {@link Iterable} under test contains at least one of the given {@link Iterable} elements.611 * <p>612 * Example :613 * <pre><code class='java'> Iterable&lt;String&gt; abc = Arrays.asList("a", "b", "c");614 *615 * // assertions will pass616 * assertThat(abc).containsAnyElementsOf(Arrays.asList("b"))617 * .containsAnyElementsOf(Arrays.asList("b", "c"))618 * .containsAnyElementsOf(Arrays.asList("a", "b", "c"))619 * .containsAnyElementsOf(Arrays.asList("a", "b", "c", "d"))620 * .containsAnyElementsOf(Arrays.asList("e", "f", "g", "b"));621 *622 * // assertions will fail623 * assertThat(abc).containsAnyElementsOf(Arrays.asList("d"));624 * assertThat(abc).containsAnyElementsOf(Arrays.asList("d", "e", "f", "g"));</code></pre>625 *626 * @param iterable the iterable whose at least one element is expected to be in the {@code Iterable} under test.627 * @return {@code this} assertion object.628 * @throws NullPointerException if the iterable of expected values is {@code null}.629 * @throws IllegalArgumentException if the iterable of expected values is empty and the {@code Iterable} under test is not empty.630 * @throws AssertionError if the {@code Iterable} under test is {@code null}.631 * @throws AssertionError if the {@code Iterable} under test does not contain any of elements from the given {@code Iterable}.632 * @since 2.9.0 / 3.9.0633 */634 @Override635 public SELF containsAnyElementsOf(Iterable<ELEMENT> iterable) {636 return containsAnyOf(toArray(iterable));637 }638 /**639 * Extract the values of the given field or property from the Iterable's elements under test into a new Iterable, this new640 * Iterable becoming the Iterable under test.641 * <p>642 * It allows you to test a property/field of the the Iterable's elements instead of testing the elements themselves, which643 * can be be much less work !644 * <p>645 * Let's take a look at an example to make things clearer :646 * <pre><code class='java'> // build a list of TolkienCharacters: a TolkienCharacter has a name, and age and a Race (a specific class)647 * // they can be public field or properties, both can be extracted.648 * List&lt;TolkienCharacter&gt; fellowshipOfTheRing = new ArrayList&lt;TolkienCharacter&gt;();649 *650 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Frodo&quot;, 33, HOBBIT));651 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Sam&quot;, 38, HOBBIT));652 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Gandalf&quot;, 2020, MAIA));653 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Legolas&quot;, 1000, ELF));654 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Pippin&quot;, 28, HOBBIT));655 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Gimli&quot;, 139, DWARF));656 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Aragorn&quot;, 87, MAN);657 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Boromir&quot;, 37, MAN));658 *659 * // let's verify the names of the TolkienCharacters in fellowshipOfTheRing :660 *661 * assertThat(fellowshipOfTheRing).extracting(&quot;name&quot;)662 * .contains(&quot;Boromir&quot;, &quot;Gandalf&quot;, &quot;Frodo&quot;)663 * .doesNotContain(&quot;Sauron&quot;, &quot;Elrond&quot;);664 *665 * // you can extract nested properties/fields like the name of the race :666 *667 * assertThat(fellowshipOfTheRing).extracting(&quot;race.name&quot;)668 * .contains(&quot;Hobbit&quot;, &quot;Elf&quot;)669 * .doesNotContain(&quot;Orc&quot;);</code></pre>670 * <p>671 * A property with the given name is searched for first. If it doesn't exist a field with the given name is looked672 * for. If the field does not exist an {@link IntrospectionError} is thrown. By default private fields are read but673 * you can change this with {@link Assertions#setAllowComparingPrivateFields(boolean)}. Trying to read a private field674 * when it's not allowed leads to an {@link IntrospectionError}.675 * <p>676 * Note that the order of extracted property/field values is consistent with the iteration order of the Iterable under677 * test, for example if it's a {@link HashSet}, you won't be able to make any assumptions on the extracted values678 * order.679 * <hr>680 * <p>681 * Extracting also support maps, that is, instead of extracting values from an Object, it extracts maps values682 * corresponding to the given keys.683 * <p>684 * Example:685 * <pre><code class='java'> Employee yoda = new Employee(1L, new Name("Yoda"), 800);686 * Employee luke = new Employee(2L, new Name("Luke"), 22);687 * Employee han = new Employee(3L, new Name("Han"), 31);688 *689 * // build two maps690 * Map&lt;String, Employee&gt; map1 = new HashMap&lt;&gt;();691 * map1.put("key1", yoda);692 * map1.put("key2", luke);693 *694 * Map&lt;String, Employee&gt; map2 = new HashMap&lt;&gt;();695 * map2.put("key1", yoda);696 * map2.put("key2", han);697 *698 * // instead of a list of objects, we have a list of maps699 * List&lt;Map&lt;String, Employee&gt;&gt; maps = asList(map1, map2);700 *701 * // extracting a property in that case = get values from maps using the property as a key702 * assertThat(maps).extracting("key2").containsExactly(luke, han);703 * assertThat(maps).extracting("key1").containsExactly(yoda, yoda);704 *705 * // type safe version706 * assertThat(maps).extracting(key2, Employee.class).containsExactly(luke, han);707 *708 * // it works with several keys, extracted values being wrapped in a Tuple709 * assertThat(maps).extracting("key1", "key2").containsExactly(tuple(yoda, luke), tuple(yoda, han));710 *711 * // unknown keys leads to null (map behavior)712 * assertThat(maps).extracting("bad key").containsExactly(null, null);</code></pre>713 *714 * @param propertyOrField the property/field to extract from the elements of the Iterable under test715 * @return a new assertion object whose object under test is the list of extracted property/field values.716 * @throws IntrospectionError if no field or property exists with the given name in one of the initial717 * Iterable's element.718 */719 @CheckReturnValue720 public AbstractListAssert<?, List<? extends Object>, Object, ObjectAssert<Object>> extracting(String propertyOrField) {721 List<Object> values = FieldsOrPropertiesExtractor.extract(actual, byName(propertyOrField));722 String extractedDescription = extractedDescriptionOf(propertyOrField);723 String description = mostRelevantDescription(info.description(), extractedDescription);724 return newListAssertInstance(values).as(description);725 }726 /**727 * Extract the result of given method invocation on the Iterable's elements under test into a new Iterable, this new728 * Iterable becoming the Iterable under test.729 * <p>730 * It allows you to test the method results of the Iterable's elements instead of testing the elements themselves. This731 * is especially useful for classes that do not conform to the Java Bean's getter specification (i.e. public String732 * toString() or public String status() instead of public String getStatus()).733 * <p>734 * Let's take a look at an example to make things clearer :735 * <pre><code class='java'> // Build a array of WesterosHouse, a WesterosHouse has a method: public String sayTheWords()736 *737 * List&lt;WesterosHouse&gt; greatHouses = new ArrayList&lt;WesterosHouse&gt;();738 * greatHouses.add(new WesterosHouse(&quot;Stark&quot;, &quot;Winter is Coming&quot;));739 * greatHouses.add(new WesterosHouse(&quot;Lannister&quot;, &quot;Hear Me Roar!&quot;));740 * greatHouses.add(new WesterosHouse(&quot;Greyjoy&quot;, &quot;We Do Not Sow&quot;));741 * greatHouses.add(new WesterosHouse(&quot;Baratheon&quot;, &quot;Our is the Fury&quot;));742 * greatHouses.add(new WesterosHouse(&quot;Martell&quot;, &quot;Unbowed, Unbent, Unbroken&quot;));743 * greatHouses.add(new WesterosHouse(&quot;Tyrell&quot;, &quot;Growing Strong&quot;));744 *745 * // let's verify the words of the great houses of Westeros:746 * assertThat(greatHouses).extractingResultOf(&quot;sayTheWords&quot;)747 * .contains(&quot;Winter is Coming&quot;, &quot;We Do Not Sow&quot;, &quot;Hear Me Roar&quot;)748 * .doesNotContain(&quot;Lannisters always pay their debts&quot;);</code></pre>749 *750 * Following requirements have to be met to extract method results:751 * <ul>752 * <li>method has to be public,</li>753 * <li>method cannot accept any arguments,</li>754 * <li>method cannot return void.</li>755 * </ul>756 * <p>757 * Note that the order of extracted results is consistent with the iteration order of the Iterable under test, for758 * example if it's a {@link HashSet}, you won't be able to make any assumptions on the extracted results order.759 *760 * @param method the name of the method which result is to be extracted from the array under test761 * @return a new assertion object whose object under test is the Iterable of extracted values.762 * @throws IllegalArgumentException if no method exists with the given name, or method is not public, or method does763 * return void, or method accepts arguments.764 */765 @CheckReturnValue766 public AbstractListAssert<?, List<? extends Object>, Object, ObjectAssert<Object>> extractingResultOf(String method) {767 // can't refactor by calling extractingResultOf(method, Object.class) as SoftAssertion would fail768 List<Object> values = FieldsOrPropertiesExtractor.extract(actual, resultOf(method));769 String extractedDescription = extractedDescriptionOfMethod(method);770 String description = mostRelevantDescription(info.description(), extractedDescription);771 return newListAssertInstance(values).as(description);772 }773 /**774 * Extract the result of given method invocation on the Iterable's elements under test into a new list of the given775 * class, this new List becoming the object under test.776 * <p>777 * It allows you to test the method results of the Iterable's elements instead of testing the elements themselves, it778 * is especially useful for classes that do not conform to the Java Bean's getter specification (i.e. public String779 * toString() or public String status() instead of public String getStatus()).780 * <p>781 * Let's take an example to make things clearer :782 * <pre><code class='java'> // Build a array of WesterosHouse, a WesterosHouse has a method: public String sayTheWords()783 * List&lt;WesterosHouse&gt; greatHouses = new ArrayList&lt;WesterosHouse&gt;();784 * greatHouses.add(new WesterosHouse(&quot;Stark&quot;, &quot;Winter is Coming&quot;));785 * greatHouses.add(new WesterosHouse(&quot;Lannister&quot;, &quot;Hear Me Roar!&quot;));786 * greatHouses.add(new WesterosHouse(&quot;Greyjoy&quot;, &quot;We Do Not Sow&quot;));787 * greatHouses.add(new WesterosHouse(&quot;Baratheon&quot;, &quot;Our is the Fury&quot;));788 * greatHouses.add(new WesterosHouse(&quot;Martell&quot;, &quot;Unbowed, Unbent, Unbroken&quot;));789 * greatHouses.add(new WesterosHouse(&quot;Tyrell&quot;, &quot;Growing Strong&quot;));790 *791 * // let's verify the words of the great houses of Westeros:792 * assertThat(greatHouses).extractingResultOf(&quot;sayTheWords&quot;, String.class)793 * .contains(&quot;Winter is Coming&quot;, &quot;We Do Not Sow&quot;, &quot;Hear Me Roar&quot;)794 * .doesNotContain(&quot;Lannisters always pay their debts&quot;);</code></pre>795 *796 * Following requirements have to be met to extract method results:797 * <ul>798 * <li>method has to be public,</li>799 * <li>method cannot accept any arguments,</li>800 * <li>method cannot return void.</li>801 * </ul>802 * <p>803 * Note that the order of extracted property/field values is consistent with the iteration order of the Iterable under804 * test, for example if it's a {@link HashSet}, you won't be able to make any assumptions of the extracted values805 * order.806 *807 * @param method the name of the method which result is to be extracted from the array under test808 * @param extractedType type of element of the extracted List809 * @return a new assertion object whose object under test is the Iterable of extracted values.810 * @throws IllegalArgumentException if no method exists with the given name, or method is not public, or method does811 * return void or method accepts arguments.812 */813 @CheckReturnValue814 public <P> AbstractListAssert<?, List<? extends P>, P, ObjectAssert<P>> extractingResultOf(String method,815 Class<P> extractedType) {816 @SuppressWarnings("unchecked")817 List<P> values = (List<P>) FieldsOrPropertiesExtractor.extract(actual, resultOf(method));818 String extractedDescription = extractedDescriptionOfMethod(method);819 String description = mostRelevantDescription(info.description(), extractedDescription);820 return newListAssertInstance(values).as(description);821 }822 /**823 * Extract the values of given field or property from the Iterable's elements under test into a new Iterable, this new824 * Iterable becoming the Iterable under test.825 * <p>826 * It allows you to test a property/field of the the Iterable's elements instead of testing the elements themselves,827 * which can be much less work !828 * <p>829 * Let's take an example to make things clearer :830 * <pre><code class='java'> // Build a list of TolkienCharacter, a TolkienCharacter has a name, and age and a Race (a specific class)831 * // they can be public field or properties, both can be extracted.832 * List&lt;TolkienCharacter&gt; fellowshipOfTheRing = new ArrayList&lt;TolkienCharacter&gt;();833 *834 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Frodo&quot;, 33, HOBBIT));835 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Sam&quot;, 38, HOBBIT));836 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Gandalf&quot;, 2020, MAIA));837 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Legolas&quot;, 1000, ELF));838 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Pippin&quot;, 28, HOBBIT));839 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Gimli&quot;, 139, DWARF));840 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Aragorn&quot;, 87, MAN);841 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Boromir&quot;, 37, MAN));842 *843 * // let's verify the names of TolkienCharacter in fellowshipOfTheRing :844 * assertThat(fellowshipOfTheRing).extracting(&quot;name&quot;, String.class)845 * .contains(&quot;Boromir&quot;, &quot;Gandalf&quot;, &quot;Frodo&quot;)846 * .doesNotContain(&quot;Sauron&quot;, &quot;Elrond&quot;);847 *848 * // you can extract nested property/field like the name of Race :849 * assertThat(fellowshipOfTheRing).extracting(&quot;race.name&quot;, String.class)850 * .contains(&quot;Hobbit&quot;, &quot;Elf&quot;)851 * .doesNotContain(&quot;Orc&quot;);</code></pre>852 *853 * A property with the given name is looked for first, if it doesn't exist then a field with the given name is looked854 * for, if the field does not exist an {@link IntrospectionError} is thrown, by default private fields are read but855 * you can change this with {@link Assertions#setAllowComparingPrivateFields(boolean)}, trying to read a private field856 * when it's not allowed leads to an {@link IntrospectionError}.857 * <p>858 * Note that the order of extracted property/field values is consistent with the iteration order of the Iterable under859 * test, for example if it's a {@link HashSet}, you won't be able to make any assumptions on the extracted values860 * order.861 * <hr>862 * <p>863 * Extracting also support maps, that is, instead of extracting values from an Object, it extract maps values864 * corresponding to the given keys.865 * <p>866 * Example:867 * <pre><code class='java'> Employee yoda = new Employee(1L, new Name("Yoda"), 800);868 * Employee luke = new Employee(2L, new Name("Luke"), 22);869 * Employee han = new Employee(3L, new Name("Han"), 31);870 *871 * // build two maps872 * Map&lt;String, Employee&gt; map1 = new HashMap&lt;&gt;();873 * map1.put("key1", yoda);874 * map1.put("key2", luke);875 *876 * Map&lt;String, Employee&gt; map2 = new HashMap&lt;&gt;();877 * map2.put("key1", yoda);878 * map2.put("key2", han);879 *880 * // instead of a list of objects, we have a list of maps881 * List&lt;Map&lt;String, Employee&gt;&gt; maps = asList(map1, map2);882 *883 * // extracting a property in that case = get values from maps using property as a key884 * assertThat(maps).extracting(key2, Employee.class).containsExactly(luke, han);885 *886 * // non type safe version887 * assertThat(maps).extracting("key2").containsExactly(luke, han);888 * assertThat(maps).extracting("key1").containsExactly(yoda, yoda);889 *890 * // it works with several keys, extracted values being wrapped in a Tuple891 * assertThat(maps).extracting("key1", "key2").containsExactly(tuple(yoda, luke), tuple(yoda, han));892 *893 * // unknown keys leads to null (map behavior)894 * assertThat(maps).extracting("bad key").containsExactly(null, null);</code></pre>895 *896 * @param propertyOrField the property/field to extract from the Iterable under test897 * @param extractingType type to return898 * @return a new assertion object whose object under test is the list of extracted property/field values.899 * @throws IntrospectionError if no field or property exists with the given name in one of the initial900 * Iterable's element.901 */902 @CheckReturnValue903 public <P> AbstractListAssert<?, List<? extends P>, P, ObjectAssert<P>> extracting(String propertyOrField,904 Class<P> extractingType) {905 @SuppressWarnings("unchecked")906 List<P> values = (List<P>) FieldsOrPropertiesExtractor.extract(actual, byName(propertyOrField));907 String extractedDescription = extractedDescriptionOf(propertyOrField);908 String description = mostRelevantDescription(info.description(), extractedDescription);909 return newListAssertInstance(values).as(description);910 }911 /**912 * Extract the values of the given fields/properties from the Iterable's elements under test into a new Iterable composed913 * of Tuples (a simple data structure), this new Iterable becoming the Iterable under test.914 * <p>915 * It allows you to test fields/properties of the the Iterable's elements instead of testing the elements themselves,916 * which can be much less work!917 * <p>918 * The Tuple data corresponds to the extracted values of the given fields/properties, for instance if you ask to919 * extract "id", "name" and "email" then each Tuple data will be composed of id, name and email extracted from the920 * element of the initial Iterable (the Tuple's data order is the same as the given fields/properties order).921 * <p>922 * Let's take an example to make things clearer :923 * <pre><code class='java'> // Build a list of TolkienCharacter, a TolkienCharacter has a name, and age and a Race (a specific class)924 * // they can be public field or properties, both can be extracted.925 * List&lt;TolkienCharacter&gt; fellowshipOfTheRing = new ArrayList&lt;TolkienCharacter&gt;();926 *927 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Frodo&quot;, 33, HOBBIT));928 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Sam&quot;, 38, HOBBIT));929 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Gandalf&quot;, 2020, MAIA));930 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Legolas&quot;, 1000, ELF));931 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Pippin&quot;, 28, HOBBIT));932 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Gimli&quot;, 139, DWARF));933 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Aragorn&quot;, 87, MAN);934 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Boromir&quot;, 37, MAN));935 *936 * // let's verify 'name' and 'age' of some TolkienCharacter in fellowshipOfTheRing :937 * assertThat(fellowshipOfTheRing).extracting(&quot;name&quot;, &quot;age&quot;)938 * .contains(tuple(&quot;Boromir&quot;, 37),939 * tuple(&quot;Sam&quot;, 38),940 * tuple(&quot;Legolas&quot;, 1000));941 *942 *943 * // extract 'name', 'age' and Race name values :944 * assertThat(fellowshipOfTheRing).extracting(&quot;name&quot;, &quot;age&quot;, &quot;race.name&quot;)945 * .contains(tuple(&quot;Boromir&quot;, 37, &quot;Man&quot;),946 * tuple(&quot;Sam&quot;, 38, &quot;Hobbit&quot;),947 * tuple(&quot;Legolas&quot;, 1000, &quot;Elf&quot;));</code></pre>948 *949 * A property with the given name is looked for first, if it doesn't exist then a field with the given name is looked950 * for, if the field does not exist an {@link IntrospectionError} is thrown, by default private fields are read but951 * you can change this with {@link Assertions#setAllowComparingPrivateFields(boolean)}, trying to read a private field952 * when it's not allowed leads to an {@link IntrospectionError}.953 * <p>954 * Note that the order of extracted property/field values is consistent with the iteration order of the Iterable under955 * test, for example if it's a {@link HashSet}, you won't be able to make any assumptions on the extracted values956 * order.957 * <hr>958 * <p>959 * Extracting also support maps, that is, instead of extracting values from an Object, it extract maps values960 * corresponding to the given keys.961 * <p>962 * Example:963 * <pre><code class='java'> Employee yoda = new Employee(1L, new Name("Yoda"), 800);964 * Employee luke = new Employee(2L, new Name("Luke"), 22);965 * Employee han = new Employee(3L, new Name("Han"), 31);966 *967 * // build two maps968 * Map&lt;String, Employee&gt; map1 = new HashMap&lt;&gt;();969 * map1.put("key1", yoda);970 * map1.put("key2", luke);971 *972 * Map&lt;String, Employee&gt; map2 = new HashMap&lt;&gt;();973 * map2.put("key1", yoda);974 * map2.put("key2", han);975 *976 * // instead of a list of objects, we have a list of maps977 * List&lt;Map&lt;String, Employee&gt;&gt; maps = asList(map1, map2);978 *979 * // extracting a property in that case = get values from maps using property as a key980 * assertThat(maps).extracting("key2").containsExactly(luke, han);981 * assertThat(maps).extracting("key1").containsExactly(yoda, yoda);982 *983 * // it works with several keys, extracted values being wrapped in a Tuple984 * assertThat(maps).extracting("key1", "key2").containsExactly(tuple(yoda, luke), tuple(yoda, han));985 *986 * // unknown keys leads to null (map behavior)987 * assertThat(maps).extracting("bad key").containsExactly(null, null);</code></pre>988 *989 * @param propertiesOrFields the properties/fields to extract from the elements of the Iterable under test990 * @return a new assertion object whose object under test is the list of Tuple with extracted properties/fields values991 * as data.992 * @throws IntrospectionError if one of the given name does not match a field or property in one of the initial993 * Iterable's element.994 */995 @CheckReturnValue996 public AbstractListAssert<?, List<? extends Tuple>, Tuple, ObjectAssert<Tuple>> extracting(String... propertiesOrFields) {997 List<Tuple> values = FieldsOrPropertiesExtractor.extract(actual, byName(propertiesOrFields));998 String extractedDescription = extractedDescriptionOf(propertiesOrFields);999 String description = mostRelevantDescription(info.description(), extractedDescription);1000 return newListAssertInstance(values).as(description);1001 }1002 /**1003 * Extract the values from Iterable's elements under test by applying an extracting function on them. The returned1004 * iterable becomes a new object under test.1005 * <p>1006 * It allows to test values from the elements in more safe way than by using {@link #extracting(String)}, as it1007 * doesn't utilize introspection.1008 * <p>1009 * Let's have a look at an example :1010 * <pre><code class='java'> // Build a list of TolkienCharacter, a TolkienCharacter has a name, and age and a Race (a specific class)1011 * // they can be public field or properties, both can be extracted.1012 * List&lt;TolkienCharacter&gt; fellowshipOfTheRing = new ArrayList&lt;TolkienCharacter&gt;();1013 *1014 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Frodo&quot;, 33, HOBBIT));1015 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Sam&quot;, 38, HOBBIT));1016 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Gandalf&quot;, 2020, MAIA));1017 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Legolas&quot;, 1000, ELF));1018 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Pippin&quot;, 28, HOBBIT));1019 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Gimli&quot;, 139, DWARF));1020 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Aragorn&quot;, 87, MAN);1021 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Boromir&quot;, 37, MAN));1022 *1023 * // this extracts the race1024 * Extractor&lt;TolkienCharacter, Race&gt; race = new Extractor&lt;TolkienCharacter, Race&gt;() {1025 * {@literal @}Override1026 * public Race extract(TolkienCharacter input) {1027 * return input.getRace();1028 * }1029 * }1030 *1031 * // fellowship has hobbitses, right, my presioussss?1032 * assertThat(fellowshipOfTheRing).extracting(race).contains(HOBBIT);</code></pre>1033 *1034 * Note that the order of extracted property/field values is consistent with the iteration order of the Iterable under1035 * test, for example if it's a {@link HashSet}, you won't be able to make any assumptions on the extracted values1036 * order.1037 *1038 * @param extractor the object transforming input object to desired one1039 * @return a new assertion object whose object under test is the list of values extracted1040 */1041 @CheckReturnValue1042 public <V> AbstractListAssert<?, List<? extends V>, V, ObjectAssert<V>> extracting(Extractor<? super ELEMENT, V> extractor) {1043 List<V> values = FieldsOrPropertiesExtractor.extract(actual, extractor);1044 return newListAssertInstance(values);1045 }1046 /**1047 * Extract the Iterable values from Iterable's elements under test by applying an Iterable extracting function on them1048 * and concatenating the result lists. The returned iterable becomes a new object under test.1049 * <p>1050 * It allows testing the results of extracting values that are represented by Iterables.1051 * <p>1052 * For example:1053 * <pre><code class='java'> CartoonCharacter bart = new CartoonCharacter("Bart Simpson");1054 * CartoonCharacter lisa = new CartoonCharacter("Lisa Simpson");1055 * CartoonCharacter maggie = new CartoonCharacter("Maggie Simpson");1056 * CartoonCharacter homer = new CartoonCharacter("Homer Simpson");1057 * homer.addChildren(bart, lisa, maggie);1058 *1059 * CartoonCharacter pebbles = new CartoonCharacter("Pebbles Flintstone");1060 * CartoonCharacter fred = new CartoonCharacter("Fred Flintstone");1061 * fred.getChildren().add(pebbles);1062 *1063 * Extractor&lt;CartoonCharacter, List&lt;CartoonCharacter&gt;&gt; childrenOf = new Extractor&lt;CartoonChildren, List&lt;CartoonChildren&gt;&gt;() {1064 * {@literal @}Override1065 * public List&lt;CartoonChildren&gt; extract(CartoonCharacter input) {1066 * return input.getChildren();1067 * }1068 * }1069 *1070 * List&lt;CartoonCharacter&gt; parents = newArrayList(homer, fred);1071 * // check children1072 * assertThat(parent).flatExtracting(childrenOf)1073 * .containsOnly(bart, lisa, maggie, pebbles);</code></pre>1074 *1075 * The order of extracted values is consisted with both the order of the collection itself, as well as the extracted1076 * collections.1077 *1078 * @param extractor the object transforming input object to an Iterable of desired ones1079 * @return a new assertion object whose object under test is the list of values extracted1080 */1081 @CheckReturnValue1082 public <V> AbstractListAssert<?, List<? extends V>, V, ObjectAssert<V>> flatExtracting(Extractor<? super ELEMENT, ? extends Collection<V>> extractor) {1083 List<V> result = newArrayList();1084 final List<? extends Collection<V>> extractedValues = FieldsOrPropertiesExtractor.extract(actual, extractor);1085 for (Collection<? extends V> iterable : extractedValues) {1086 result.addAll(iterable);1087 }1088 return newListAssertInstance(result);1089 }1090 /**1091 * Extract from Iterable's elements the Iterable/Array values corresponding to the given property/field name and1092 * concatenate them into a single list becoming the new object under test.1093 * <p>1094 * It allows testing the elements of extracting values that are represented by iterables or arrays.1095 * <p>1096 * For example:1097 * <pre><code class='java'> CartoonCharacter bart = new CartoonCharacter("Bart Simpson");1098 * CartoonCharacter lisa = new CartoonCharacter("Lisa Simpson");1099 * CartoonCharacter maggie = new CartoonCharacter("Maggie Simpson");1100 * CartoonCharacter homer = new CartoonCharacter("Homer Simpson");1101 * homer.addChildren(bart, lisa, maggie);1102 *1103 * CartoonCharacter pebbles = new CartoonCharacter("Pebbles Flintstone");1104 * CartoonCharacter fred = new CartoonCharacter("Fred Flintstone");1105 * fred.getChildren().add(pebbles);1106 *1107 * List&lt;CartoonCharacter&gt; parents = newArrayList(homer, fred);1108 * // check children1109 * assertThat(parents).flatExtracting("children")1110 * .containsOnly(bart, lisa, maggie, pebbles);</code></pre>1111 *1112 * The order of extracted values is consisted with both the order of the collection itself, as well as the extracted1113 * collections.1114 *1115 * @param fieldOrPropertyName the object transforming input object to an Iterable of desired ones1116 * @return a new assertion object whose object under test is the list of values extracted1117 * @throws IllegalArgumentException if one of the extracted property value was not an array or an iterable.1118 */1119 @CheckReturnValue1120 public AbstractListAssert<?, List<? extends Object>, Object, ObjectAssert<Object>> flatExtracting(String fieldOrPropertyName) {1121 List<Object> extractedValues = newArrayList();1122 List<?> extractedGroups = FieldsOrPropertiesExtractor.extract(actual, byName(fieldOrPropertyName));1123 for (Object group : extractedGroups) {1124 // expecting group to be an iterable or an array1125 if (isArray(group)) {1126 int size = Array.getLength(group);1127 for (int i = 0; i < size; i++) {1128 extractedValues.add(Array.get(group, i));1129 }1130 } else if (group instanceof Iterable) {1131 Iterable<?> iterable = (Iterable<?>) group;1132 for (Object value : iterable) {1133 extractedValues.add(value);1134 }1135 } else {1136 CommonErrors.wrongElementTypeForFlatExtracting(group);1137 }1138 }1139 return newListAssertInstance(extractedValues);1140 }1141 /**1142 * Extract the given properties/fields values from each {@code Iterable}'s element and1143 * flatten the extracted values in a list that is used as the new object under test.1144 * <p>1145 * Given 2 properties, if the extracted values were not flattened, instead having a simple list like :1146 * <pre>element1.value1, element1.value2, element2.value1, element2.value2, ... </pre>1147 * ... we would get a list of list :1148 * <pre>list(element1.value1, element1.value2), list(element2.value1, element2.value2), ... </pre>1149 * <p>1150 * Code example:1151 * <pre><code class='java'> // fellowshipOfTheRing is a List&lt;TolkienCharacter&gt;1152 *1153 * // values are extracted in order and flattened : age1, name1, age2, name2, age3 ...1154 * assertThat(fellowshipOfTheRing).flatExtracting("age", "name")1155 * .contains(33 ,"Frodo",1156 * 1000, "Legolas",1157 * 87, "Aragorn");</code></pre>1158 *1159 * @param fieldOrPropertyNames the field and/or property names to extract from each actual {@code Iterable}'s element1160 * @return a new assertion object whose object under test is a flattened list of all extracted values.1161 * @throws IllegalArgumentException if fieldOrPropertyNames vararg is null or empty1162 * @since 2.5.01163 */1164 @CheckReturnValue1165 public AbstractListAssert<?, List<? extends Object>, Object, ObjectAssert<Object>> flatExtracting(String... fieldOrPropertyNames) {1166 List<Object> extractedValues = newArrayList();1167 for (Tuple tuple : FieldsOrPropertiesExtractor.extract(actual, Extractors.byName(fieldOrPropertyNames))) {1168 extractedValues.addAll(tuple.toList());1169 }1170 return newListAssertInstance(extractedValues);1171 }1172 /**1173 * {@inheritDoc}1174 */1175 @Override1176 public SELF containsExactlyElementsOf(Iterable<? extends ELEMENT> iterable) {1177 return containsExactly(toArray(iterable));1178 }1179 /**1180 * {@inheritDoc}1181 */1182 @Override1183 public SELF containsOnlyElementsOf(Iterable<? extends ELEMENT> iterable) {1184 return containsOnly(toArray(iterable));1185 }1186 /**1187 * {@inheritDoc}1188 */1189 @Override1190 public SELF hasSameElementsAs(Iterable<? extends ELEMENT> iterable) {1191 return containsOnlyElementsOf(iterable);1192 }1193 /**1194 * Allows to set a comparator to compare properties or fields of elements with the given names.1195 * A typical usage is for comparing fields of numeric type at a given precision.1196 * <p>1197 * To be used, comparators need to be specified by this method <b>before</b> calling any of:1198 * <ul>1199 * <li>{@link #usingFieldByFieldElementComparator}</li>1200 * <li>{@link #usingElementComparatorOnFields}</li>1201 * <li>{@link #usingElementComparatorIgnoringFields}</li>1202 * <li>{@link #usingRecursiveFieldByFieldElementComparator}</li>1203 * </ul>1204 * <p>1205 * Comparators specified by this method have precedence over comparators specified by1206 * {@link #usingComparatorForElementFieldsWithType(Comparator, Class) usingComparatorForElementFieldsWithType}.1207 * <p>1208 * Example:1209 *1210 * <pre><code class='java'> public class TolkienCharacter {1211 * private String name;1212 * private double height;1213 * // constructor omitted1214 * }1215 *1216 * TolkienCharacter frodo = new TolkienCharacter(&quot;Frodo&quot;, 1.2);1217 * TolkienCharacter tallerFrodo = new TolkienCharacter(&quot;Frodo&quot;, 1.3);1218 * TolkienCharacter reallyTallFrodo = new TolkienCharacter(&quot;Frodo&quot;, 1.9);1219 *1220 * Comparator&lt;Double&gt; closeEnough = new Comparator&lt;Double&gt;() {1221 * double precision = 0.5;1222 * public int compare(Double d1, Double d2) {1223 * return Math.abs(d1 - d2) &lt;= precision ? 0 : 1;1224 * }1225 * };1226 *1227 * // assertions will pass1228 * assertThat(asList(frodo)).usingComparatorForElementFieldsWithNames(closeEnough, &quot;height&quot;)1229 * .usingFieldByFieldElementComparator()1230 * .contains(tallerFrodo);1231 *1232 * assertThat(asList(frodo)).usingComparatorForElementFieldsWithNames(closeEnough, &quot;height&quot;)1233 * .usingElementComparatorOnFields(&quot;height&quot;)1234 * .contains(tallerFrodo);1235 *1236 * assertThat(asList(frodo)).usingComparatorForElementFieldsWithNames(closeEnough, &quot;height&quot;)1237 * .usingElementComparatorIgnoringFields(&quot;name&quot;)1238 * .contains(tallerFrodo);1239 *1240 * assertThat(asList(frodo)).usingComparatorForElementFieldsWithNames(closeEnough, &quot;height&quot;)1241 * .usingRecursiveFieldByFieldElementComparator()1242 * .contains(tallerFrodo);1243 *1244 * // assertion will fail1245 * assertThat(asList(frodo)).usingComparatorForElementFieldsWithNames(closeEnough, &quot;height&quot;)1246 * .usingFieldByFieldElementComparator()1247 * .containsExactly(reallyTallFrodo);</code></pre>1248 *1249 * @param comparator the {@link java.util.Comparator} to use1250 * @param elementPropertyOrFieldNames the names of the properties and/or fields of the elements the comparator should be used for1251 * @return {@code this} assertions object1252 * @since 2.5.0 / 3.5.01253 */1254 @CheckReturnValue1255 public <T> SELF usingComparatorForElementFieldsWithNames(Comparator<T> comparator,1256 String... elementPropertyOrFieldNames) {1257 for (String elementPropertyOrField : elementPropertyOrFieldNames) {1258 comparatorsForElementPropertyOrFieldNames.put(elementPropertyOrField, comparator);1259 }1260 return myself;1261 }1262 /**1263 * Allows to set a specific comparator to compare properties or fields of elements with the given type.1264 * A typical usage is for comparing fields of numeric type at a given precision.1265 * <p>1266 * To be used, comparators need to be specified by this method <b>before</b> calling any of:1267 * <ul>1268 * <li>{@link #usingFieldByFieldElementComparator}</li>1269 * <li>{@link #usingElementComparatorOnFields}</li>1270 * <li>{@link #usingElementComparatorIgnoringFields}</li>1271 * <li>{@link #usingRecursiveFieldByFieldElementComparator}</li>1272 * </ul>1273 * <p>1274 * Comparators specified by {@link #usingComparatorForElementFieldsWithNames(Comparator, String...) usingComparatorForElementFieldsWithNames}1275 * have precedence over comparators specified by this method.1276 * <p>1277 * Example:1278 * <pre><code class='java'> public class TolkienCharacter {1279 * private String name;1280 * private double height;1281 * // constructor omitted1282 * }1283 * TolkienCharacter frodo = new TolkienCharacter(&quot;Frodo&quot;, 1.2);1284 * TolkienCharacter tallerFrodo = new TolkienCharacter(&quot;Frodo&quot;, 1.3);1285 * TolkienCharacter reallyTallFrodo = new TolkienCharacter(&quot;Frodo&quot;, 1.9);1286 *1287 * Comparator&lt;Double&gt; closeEnough = new Comparator&lt;Double&gt;() {1288 * double precision = 0.5;1289 * public int compare(Double d1, Double d2) {1290 * return Math.abs(d1 - d2) &lt;= precision ? 0 : 1;1291 * }1292 * };1293 *1294 * // assertions will pass1295 * assertThat(Arrays.asList(frodo)).usingComparatorForElementFieldsWithType(closeEnough, Double.class)1296 * .usingFieldByFieldElementComparator()1297 * .contains(tallerFrodo);1298 *1299 * assertThat(Arrays.asList(frodo)).usingComparatorForElementFieldsWithType(closeEnough, Double.class)1300 * .usingElementComparatorOnFields(&quot;height&quot;)1301 * .contains(tallerFrodo);1302 *1303 * assertThat(Arrays.asList(frodo)).usingComparatorForElementFieldsWithType(closeEnough, Double.class)1304 * .usingElementComparatorIgnoringFields(&quot;name&quot;)1305 * .contains(tallerFrodo);1306 *1307 * assertThat(Arrays.asList(frodo)).usingComparatorForElementFieldsWithType(closeEnough, Double.class)1308 * .usingRecursiveFieldByFieldElementComparator()1309 * .contains(tallerFrodo);1310 *1311 * // assertion will fail1312 * assertThat(Arrays.asList(frodo)).usingComparatorForElementFieldsWithType(closeEnough, Double.class)1313 * .usingFieldByFieldElementComparator()1314 * .contains(reallyTallFrodo);</code></pre>1315 *1316 * @param comparator the {@link java.util.Comparator} to use1317 * @param type the {@link java.lang.Class} of the type of the element fields the comparator should be used for1318 * @return {@code this} assertions object1319 * @since 2.5.0 / 3.5.01320 */1321 @CheckReturnValue1322 public <T> SELF usingComparatorForElementFieldsWithType(Comparator<T> comparator, Class<T> type) {1323 comparatorsForElementPropertyOrFieldTypes.put(type, comparator);1324 return myself;1325 }1326 /**1327 * Allows to set a specific comparator for the given type of elements or their fields.1328 * Extends {@link #usingComparatorForElementFieldsWithType} by applying comparator specified for given type1329 * to elements themselves, not only to their fields.1330 * <p>1331 * Usage of this method affects comparators set by next methods:1332 * <ul>1333 * <li>{@link #usingFieldByFieldElementComparator}</li>1334 * <li>{@link #usingElementComparatorOnFields}</li>1335 * <li>{@link #usingElementComparatorIgnoringFields}</li>1336 * <li>{@link #usingRecursiveFieldByFieldElementComparator}</li>1337 * </ul>1338 * <p>1339 * Example:1340 * <pre><code class='java'>1341 * // assertion will pass1342 * assertThat(asList("some", new BigDecimal("4.2")))1343 * .usingComparatorForType(BIG_DECIMAL_COMPARATOR, BigDecimal.class)1344 * .contains(new BigDecimal("4.20"));1345 * </code></pre>1346 * </p>1347 *1348 * @param comparator the {@link java.util.Comparator} to use1349 * @param type the {@link java.lang.Class} of the type of the element or element fields the comparator should be used for1350 * @return {@code this} assertions object1351 * @since 2.9.0 / 3.9.01352 */1353 @CheckReturnValue1354 public <T> SELF usingComparatorForType(Comparator<T> comparator, Class<T> type) {1355 if (iterables.getComparator() == null) {1356 usingElementComparator(new ExtendedByTypesComparator(comparatorsByType));1357 }1358 comparatorsForElementPropertyOrFieldTypes.put(type, comparator);1359 comparatorsByType.put(type, comparator);1360 return myself;1361 }1362 /**1363 * Use field/property by field/property comparison (including inherited fields/properties) instead of relying on1364 * actual type A <code>equals</code> method to compare group elements for incoming assertion checks. Private fields1365 * are included but this can be disabled using {@link Assertions#setAllowExtractingPrivateFields(boolean)}.1366 * <p>1367 * This can be handy if <code>equals</code> method of the objects to compare does not suit you.1368 * <p>1369 * Note that the comparison is <b>not</b> recursive, if one of the fields/properties is an Object, it will be compared1370 * to the other field/property using its <code>equals</code> method.1371 * <p>1372 * You can specify a custom comparator per name or type of element field with1373 * {@link #usingComparatorForElementFieldsWithNames(Comparator, String...)}1374 * and {@link #usingComparatorForElementFieldsWithType(Comparator, Class)}.1375 * <p>1376 * Example:1377 * <pre><code class='java'> TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT);1378 * TolkienCharacter frodoClone = new TolkienCharacter("Frodo", 33, HOBBIT);1379 *1380 * // Fail if equals has not been overridden in TolkienCharacter as equals default implementation only compares references1381 * assertThat(newArrayList(frodo)).contains(frodoClone);1382 *1383 * // frodo and frodoClone are equals when doing a field by field comparison.1384 * assertThat(newArrayList(frodo)).usingFieldByFieldElementComparator().contains(frodoClone);</code></pre>1385 *1386 * @return {@code this} assertion object.1387 */1388 @CheckReturnValue1389 public SELF usingFieldByFieldElementComparator() {1390 return usingExtendedByTypesElementComparator(new FieldByFieldComparator(comparatorsForElementPropertyOrFieldNames,1391 comparatorsForElementPropertyOrFieldTypes));1392 }1393 /**1394 * Use a recursive field/property by field/property comparison (including inherited fields/properties)1395 * instead of relying on actual type <code>equals</code> method to compare group elements for incoming1396 * assertion checks. This can be useful if actual's {@code equals} implementation does not suit you.1397 * <p>1398 * The recursive property/field comparison is <b>not</b> applied on fields having a custom {@code equals}1399 * implementation, i.e. the overridden {@code equals} method will be used instead of a field/property by field/property1400 * comparison.1401 * <p>1402 * The recursive comparison handles cycles.1403 * <p>1404 * You can specify a custom comparator per (nested) name or type of element field with1405 * {@link #usingComparatorForElementFieldsWithNames(Comparator, String...) usingComparatorForElementFieldsWithNames}1406 * and {@link #usingComparatorForElementFieldsWithType(Comparator, Class) usingComparatorForElementFieldsWithType}.1407 * <p>1408 * The objects to compare can be of different types but must have the same properties/fields. For example if actual1409 * object has a {@code name} String field, the other object must also have one.1410 * <p>1411 * If an object has a field and a property with the same name, the property value will be used over the field.1412 * <p>1413 * Example:1414 * <pre><code class='java'> TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT);1415 * TolkienCharacter pippin = new TolkienCharacter("Pippin", 28, HOBBIT);1416 * frodo.setFriend(pippin);1417 * pippin.setFriend(frodo);1418 *1419 * TolkienCharacter frodoClone = new TolkienCharacter("Frodo", 33, HOBBIT);1420 * TolkienCharacter pippinClone = new TolkienCharacter("Pippin", 28, HOBBIT);1421 * frodoClone.setFriend(pippinClone);1422 * pippinClone.setFriend(frodoClone);1423 *1424 * List&lt;TolkienCharacter&gt; hobbits = Arrays.asList(frodo, pippin);1425 *1426 * // fails if equals has not been overridden in TolkienCharacter as it would compares object references1427 * assertThat(hobbits).contains(frodoClone, pippinClone);1428 *1429 * // frodo/frodoClone and pippin/pippinClone are equals when doing a recursive property/field by property/field comparison1430 * assertThat(hobbits).usingRecursiveFieldByFieldElementComparator()1431 * .contains(frodoClone, pippinClone);</code>1432 * </pre>1433 *1434 * @return {@code this} assertion object.1435 * @since 2.5.0 / 3.5.01436 */1437 @CheckReturnValue1438 public SELF usingRecursiveFieldByFieldElementComparator() {1439 return usingExtendedByTypesElementComparator(new RecursiveFieldByFieldComparator(comparatorsForElementPropertyOrFieldNames,1440 comparatorsForElementPropertyOrFieldTypes));1441 }1442 /**1443 * Use field/property by field/property comparison on the <b>given fields/properties only</b> (including inherited1444 * fields/properties) instead of relying on actual type A <code>equals</code> method to compare group elements for1445 * incoming assertion checks. Private fields are included but this can be disabled using1446 * {@link Assertions#setAllowExtractingPrivateFields(boolean)}.1447 * <p>1448 * This can be handy if <code>equals</code> method of the objects to compare does not suit you.1449 * <p>1450 * You can specify a custom comparator per name or type of element field with1451 * {@link #usingComparatorForElementFieldsWithNames(Comparator, String...)}1452 * and {@link #usingComparatorForElementFieldsWithType(Comparator, Class)}.1453 * <p>1454 * Note that the comparison is <b>not</b> recursive, if one of the fields/properties is an Object, it will be compared1455 * to the other field/property using its <code>equals</code> method.1456 * </p>1457 * Example:1458 * <pre><code class='java'> TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT);1459 * TolkienCharacter sam = new TolkienCharacter("Sam", 38, HOBBIT);1460 *1461 * // frodo and sam both are hobbits, so they are equals when comparing only race1462 * assertThat(newArrayList(frodo)).usingElementComparatorOnFields("race").contains(sam); // OK1463 *1464 * // ... but not when comparing both name and race1465 * assertThat(newArrayList(frodo)).usingElementComparatorOnFields("name", "race").contains(sam); // FAIL</code></pre>1466 *1467 * @param fields the fields/properties to compare using element comparators1468 * @return {@code this} assertion object.1469 */1470 @CheckReturnValue1471 public SELF usingElementComparatorOnFields(String... fields) {1472 return usingExtendedByTypesElementComparator(new OnFieldsComparator(comparatorsForElementPropertyOrFieldNames,1473 comparatorsForElementPropertyOrFieldTypes,1474 fields));1475 }1476 protected SELF usingComparisonStrategy(ComparisonStrategy comparisonStrategy) {1477 iterables = new Iterables(comparisonStrategy);1478 return myself;1479 }1480 /**1481 * Use field/property by field/property comparison on all fields/properties <b>except</b> the given ones (including inherited1482 * fields/properties) instead of relying on actual type A <code>equals</code> method to compare group elements for1483 * incoming assertion checks. Private fields are included but this can be disabled using1484 * {@link Assertions#setAllowExtractingPrivateFields(boolean)}.1485 * <p>1486 * This can be handy if <code>equals</code> method of the objects to compare does not suit you.1487 * <p>1488 * You can specify a custom comparator per name or type of element field with1489 * {@link #usingComparatorForElementFieldsWithNames(Comparator, String...)}1490 * and {@link #usingComparatorForElementFieldsWithType(Comparator, Class)}.1491 * <p>1492 * Note that the comparison is <b>not</b> recursive, if one of the fields/properties is an Object, it will be compared1493 * to the other field/property using its <code>equals</code> method.1494 * </p>1495 * Example:1496 * <pre><code class='java'> TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT);1497 * TolkienCharacter sam = new TolkienCharacter("Sam", 38, HOBBIT);1498 *1499 * // frodo and sam both are hobbits, so they are equals when comparing only race (i.e. ignoring all other fields)1500 * assertThat(newArrayList(frodo)).usingElementComparatorIgnoringFields("name", "age").contains(sam); // OK1501 *1502 * // ... but not when comparing both name and race1503 * assertThat(newArrayList(frodo)).usingElementComparatorIgnoringFields("age").contains(sam); // FAIL</code></pre>1504 *1505 * @return {@code this} assertion object.1506 */1507 @CheckReturnValue1508 public SELF usingElementComparatorIgnoringFields(String... fields) {1509 return usingExtendedByTypesElementComparator(new IgnoringFieldsComparator(comparatorsForElementPropertyOrFieldNames,1510 comparatorsForElementPropertyOrFieldTypes,1511 fields));1512 }1513 /**1514 * Enable hexadecimal representation of Iterable elements instead of standard representation in error messages.1515 * <p>1516 * It can be useful to better understand what the error was with a more meaningful error message.1517 * <p>1518 * Example1519 * <pre><code class='java'> final List&lt;Byte&gt; bytes = newArrayList((byte) 0x10, (byte) 0x20);</code></pre>1520 *1521 * With standard error message:1522 * <pre><code class='java'> assertThat(bytes).contains((byte) 0x30);1523 *...

Full Screen

Full Screen

usingExtendedByTypesElementComparator

Using AI Code Generation

copy

Full Screen

1import org.junit.Test;2import static org.assertj.core.api.Assertions.assertThat;3public class UsingExtendedByTypesElementComparatorTest {4 public void testUsingExtendedByTypesElementComparator() {5 assertThat(new String[] { "a", "b" })6 .usingExtendedByTypesElementComparator()7 .contains("a", "b");8 }9}

Full Screen

Full Screen

usingExtendedByTypesElementComparator

Using AI Code Generation

copy

Full Screen

1import org.junit.jupiter.api.Test;2import java.util.ArrayList;3import java.util.List;4import static org.assertj.core.api.Assertions.assertThat;5public class AssertJUsingExtendedByTypesElementComparatorExample {6 public void usingExtendedByTypesElementComparatorTest() {7 List<String> actual = new ArrayList<>();8 actual.add("a");9 actual.add("b");10 actual.add("c");11 assertThat(actual).usingExtendedByTypesElementComparator().contains("a", "b", "c");12 }13}

Full Screen

Full Screen

usingExtendedByTypesElementComparator

Using AI Code Generation

copy

Full Screen

1import static org.assertj.core.api.Assertions.*;2import static org.assertj.core.api.Assertions.assertThat;3import java.util.ArrayList;4import java.util.List;5import org.assertj.core.api.AbstractIterableAssert;6import org.junit.Test;7public class IterableAssert_usingExtendedByTypesElementComparator_Test {8 public void test() {9 List<AbstractIterableAssert_usingExtendedByTypesElementComparator_Test_Person> persons = new ArrayList<>();10 persons.add(new AbstractIterableAssert_usingExtendedByTypesElementComparator_Test_Person("John", 35));11 persons.add(new AbstractIterableAssert_usingExtendedByTypesElementComparator_Test_Person("Jane", 33));12 persons.add(new AbstractIterableAssert_usingExtendedByTypesElementComparator_Test_Person("Jack", 33));13 assertThat(persons).usingElementComparatorOnFields("age").contains(new AbstractIterableAssert_usingExtendedByTypesElementComparator_Test_Person("Jack", 33));14 assertThat(persons).usingExtendedByTypesElementComparator().usingElementComparatorOnFields("age").contains(new AbstractIterableAssert_usingExtendedByTypesElementComparator_Test_Person("Jack", 33));15 }16}17class AbstractIterableAssert_usingExtendedByTypesElementComparator_Test_Person {18 private final String name;19 private final int age;20 public AbstractIterableAssert_usingExtendedByTypesElementComparator_Test_Person(String name, int age) {21 this.name = name;22 this.age = age;23 }24 public String getName() {25 return name;26 }27 public int getAge() {28 return age;29 }30 public String toString() {31 return "Person [name=" + name + ", age=" + age + "]";32 }33}34 at org.junit.Assert.assertEquals(Assert.java:115)35 at org.junit.Assert.assertEquals(Assert.java:144)36 at org.assertj.core.api.AbstractIterableAssert_usingExtendedByTypesElementComparator_Test.test(AbstractIterableAssert_usingExtendedByTypesElementComparator_Test.java:28)

Full Screen

Full Screen

usingExtendedByTypesElementComparator

Using AI Code Generation

copy

Full Screen

1assertThat(employees).usingExtendedByTypesElementComparator().containsOnly(2 new Employee("John", 34, "NY"),3 new Employee("Jane", 35, "NY"),4 new Employee("Jack", 36, "NY")5);6assertThat(employees).usingRecursiveFieldByFieldElementComparator().containsOnly(7 new Employee("John", 34, "NY"),8 new Employee("Jane", 35, "NY"),9 new Employee("Jack", 36, "NY")10);11assertThat(employees).usingElementComparatorOnFields("age").containsOnly(12 new Employee("John", 34, "NY"),13 new Employee("Jane", 35, "NY"),14 new Employee("Jack", 36, "NY")15);16assertThat(employees).usingElementComparatorOnFields("age", "city").containsOnly(17 new Employee("John", 34, "NY"),18 new Employee("Jane", 35, "NY"),19 new Employee("Jack", 36, "NY")20);21assertThat(employees).usingElementComparatorIgnoringFields("city").containsOnly(22 new Employee("John", 34, "NY"),23 new Employee("Jane", 35, "NY"),24 new Employee("Jack", 36, "NY")25);26assertThat(employees).usingComparatorForElementFieldsWithNames(CASE_INSENSITIVE_STRING_COMPARATOR,27 "name").containsOnly(28 new Employee("John", 34, "NY"),29 new Employee("Jane", 35, "NY"),30 new Employee("Jack", 36, "NY")31);32assertThat(employees).usingComparatorForElementFieldsWithType(CASE_INSENSITIVE_STRING_COMPARATOR,33 String.class).containsOnly(34 new Employee("John", 34, "NY"),

Full Screen

Full Screen

usingExtendedByTypesElementComparator

Using AI Code Generation

copy

Full Screen

1import static org.assertj.core.api.Assertions.assertThat;2import static org.assertj.core.api.Assertions.within;3import static org.assertj.core.util.Lists.newArrayList;4import static org.assertj.core.util.Sets.newLinkedHashSet;5import static org.assertj.core.util.Sets.newTreeSet;6import static org.assertj.core.util.Maps.newHashMap;7import static org.assertj.core.util.Maps.newLinkedHashMap;8import static org.assertj.core.util.Maps.newTreeMap;9import org.assertj.core.api.AbstractIterableAssert;10import org.assertj.core.api.Assertions;11import org.assertj.core.api.ExtendedByTypesElementComparator;12import org.assertj.core.internal.Iterables;13import org.assertj.core.internal.Objects;14import org.assertj.core.util.introspection.IntrospectionError;15import org.junit.Test;16import java.util.List;17import java.util.Map;18import java.util.Set;19import java.util.TreeMap;20import java.util.TreeSet;21public class ExtendedByTypesElementComparatorTest {22 public void should_pass_if_iterables_are_equal_using_extended_by_types_element_comparator() {23 List<String> list1 = newArrayList("a", "b", "c");24 List<String> list2 = newArrayList("a", "b", "c");25 assertThat(list1).usingExtendedByTypesElementComparator().isEqualTo(list2);26 }27 public void should_pass_if_iterables_are_equal_using_extended_by_types_element_comparator_with_null() {28 List<String> list1 = newArrayList("a", null, "c");29 List<String> list2 = newArrayList("a", null, "c");30 assertThat(list1).usingExtendedByTypesElementComparator().isEqualTo(list2);31 }32 public void should_pass_if_iterables_are_equal_using_extended_by_types_element_comparator_with_double() {33 List<Double> list1 = newArrayList(1.0, 2.0, 3.0);34 List<Double> list2 = newArrayList(1.0, 2.0, 3.0);35 assertThat(list1).usingExtendedByTypesElementComparator().isEqualTo(list2);36 }37 public void should_pass_if_sets_are_equal_using_extended_by_types_element_comparator() {38 Set<String> set1 = newLinkedHashSet("a", "b", "c");

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 AbstractIterableAssert

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful