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

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

Source:AbstractIterableAssert.java Github

copy

Full Screen

...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 }2845 private static String removeAssert(String text) {2846 return text.endsWith(ASSERT) ? text.substring(0, text.length() - ASSERT.length()) : text;2847 }2848 /**2849 * Filters the iterable under test keeping only elements matching the given {@link Predicate}.2850 * <p>2851 * Example : check old employees whose age &gt; 100:2852 *2853 * <pre><code class='java'> Employee yoda = new Employee(1L, new Name("Yoda"), 800);2854 * Employee obiwan = new Employee(2L, new Name("Obiwan"), 800);2855 * Employee luke = new Employee(3L, new Name("Luke", "Skywalker"), 26);2856 *2857 * List&lt;Employee&gt; employees = newArrayList(yoda, luke, obiwan);2858 *2859 * assertThat(employees).filteredOn(employee -&gt; employee.getAge() &gt; 100)2860 * .containsOnly(yoda, obiwan);</code></pre>2861 *2862 * @param predicate the filter predicate2863 * @return a new assertion object with the filtered iterable under test2864 * @throws IllegalArgumentException if the given predicate is {@code null}.2865 */2866 public SELF filteredOn(Predicate<? super ELEMENT> predicate) {2867 return internalFilteredOn(predicate);2868 }2869 /**2870 * {@inheritDoc}2871 */2872 @Override2873 public SELF allMatch(Predicate<? super ELEMENT> predicate) {2874 iterables.assertAllMatch(info, actual, predicate, PredicateDescription.GIVEN);2875 return myself;2876 }2877 /**2878 * {@inheritDoc}2879 */2880 @Override2881 public SELF allMatch(Predicate<? super ELEMENT> predicate, String predicateDescription) {2882 iterables.assertAllMatch(info, actual, predicate, new PredicateDescription(predicateDescription));2883 return myself;2884 }2885 /**2886 * {@inheritDoc}2887 */2888 @Override2889 public SELF allSatisfy(Consumer<? super ELEMENT> requirements) {2890 iterables.assertAllSatisfy(info, actual, requirements);2891 return myself;2892 }2893 @Override2894 public SELF anyMatch(Predicate<? super ELEMENT> predicate) {2895 iterables.assertAnyMatch(info, actual, predicate, PredicateDescription.GIVEN);2896 return myself;2897 }2898 /**2899 * Verifies that the zipped pairs of actual and other elements, i.e: (actual 1st element, other 1st element), (actual 2nd element, other 2nd element), ...2900 * all satisfy the given {@code zipRequirements}.2901 * <p>2902 * This assertion assumes that actual and other have the same size but they can contain different type of elements2903 * making it handy to compare objects converted to another type, for example Domain and View/DTO objects.2904 * <p>2905 * Example:2906 * <pre><code class='java'> List&lt;Adress&gt; addressModels = findGoodRestaurants();2907 * List&lt;AdressView&gt; addressViews = convertToView(addressModels);2908 *2909 * // compare addressViews and addressModels respective paired elements.2910 * assertThat(addressViews).zipSatisfy(addressModels, (AdressView view, Adress model) -&gt; {2911 * assertThat(view.getZipcode() + ' ' + view.getCity()).isEqualTo(model.getCityLine());2912 * assertThat(view.getStreet()).isEqualTo(model.getStreet().toUpperCase());2913 * });</code></pre>2914 *2915 * @param <OTHER_ELEMENT> the type of the other iterable elements.2916 * @param other the iterable to zip actual with.2917 * @param zipRequirements the given requirements that each pair must satisfy.2918 * @return {@code this} assertion object.2919 * @throws NullPointerException if the given zipRequirements {@link BiConsumer} is {@code null}.2920 * @throws NullPointerException if the other iterable to zip actual with is {@code null}.2921 * @throws AssertionError if the {@code Iterable} under test is {@code null}.2922 * @throws AssertionError if actual and other don't have the same size.2923 * @throws AssertionError if one or more pairs don't satisfy the given requirements.2924 * @since 3.9.02925 */2926 public <OTHER_ELEMENT> SELF zipSatisfy(Iterable<OTHER_ELEMENT> other,2927 BiConsumer<? super ELEMENT, OTHER_ELEMENT> zipRequirements) {2928 iterables.assertZipSatisfy(info, actual, other, zipRequirements);2929 return myself;2930 }2931 /**2932 * {@inheritDoc}2933 */2934 @Override2935 public SELF anySatisfy(Consumer<? super ELEMENT> requirements) {2936 iterables.assertAnySatisfy(info, actual, requirements);2937 return myself;2938 }2939 /**2940 * {@inheritDoc}2941 */2942 @Override2943 public SELF noneSatisfy(Consumer<? super ELEMENT> restrictions) {2944 iterables.assertNoneSatisfy(info, actual, restrictions);2945 return myself;2946 }2947 // override methods to avoid compilation error when chaining an AbstractAssert method with a AbstractIterableAssert2948 // one on raw types.2949 @Override2950 @CheckReturnValue2951 public SELF as(String description, Object... args) {2952 return super.as(description, args);2953 }2954 @Override2955 @CheckReturnValue2956 public SELF as(Description description) {2957 return super.as(description);2958 }2959 @Override2960 @CheckReturnValue2961 public SELF describedAs(Description description) {2962 return super.describedAs(description);2963 }2964 @Override2965 @CheckReturnValue2966 public SELF describedAs(String description, Object... args) {2967 return super.describedAs(description, args);2968 }2969 @Override2970 public SELF doesNotHave(Condition<? super ACTUAL> condition) {2971 return super.doesNotHave(condition);2972 }2973 @Override2974 public SELF doesNotHaveSameClassAs(Object other) {2975 return super.doesNotHaveSameClassAs(other);2976 }2977 @Override2978 public SELF has(Condition<? super ACTUAL> condition) {2979 return super.has(condition);2980 }2981 @Override2982 public SELF hasSameClassAs(Object other) {2983 return super.hasSameClassAs(other);2984 }2985 @Override2986 public SELF hasToString(String expectedToString) {2987 return super.hasToString(expectedToString);2988 }2989 @Override2990 public SELF is(Condition<? super ACTUAL> condition) {2991 return super.is(condition);2992 }2993 @Override2994 public SELF isEqualTo(Object expected) {2995 return super.isEqualTo(expected);2996 }2997 @Override2998 public SELF isExactlyInstanceOf(Class<?> type) {2999 return super.isExactlyInstanceOf(type);3000 }3001 @Override3002 public SELF isIn(Iterable<?> values) {3003 return super.isIn(values);3004 }3005 @Override3006 public SELF isIn(Object... values) {3007 return super.isIn(values);3008 }3009 @Override3010 public SELF isInstanceOf(Class<?> type) {3011 return super.isInstanceOf(type);3012 }3013 @Override3014 public SELF isInstanceOfAny(Class<?>... types) {3015 return super.isInstanceOfAny(types);3016 }3017 @Override3018 public SELF isNot(Condition<? super ACTUAL> condition) {3019 return super.isNot(condition);3020 }3021 @Override3022 public SELF isNotEqualTo(Object other) {3023 return super.isNotEqualTo(other);3024 }3025 @Override3026 public SELF isNotExactlyInstanceOf(Class<?> type) {3027 return super.isNotExactlyInstanceOf(type);3028 }3029 @Override3030 public SELF isNotIn(Iterable<?> values) {3031 return super.isNotIn(values);3032 }3033 @Override3034 public SELF isNotIn(Object... values) {3035 return super.isNotIn(values);3036 }3037 @Override3038 public SELF isNotInstanceOf(Class<?> type) {3039 return super.isNotInstanceOf(type);3040 }3041 @Override3042 public SELF isNotInstanceOfAny(Class<?>... types) {3043 return super.isNotInstanceOfAny(types);3044 }3045 @Override3046 public SELF isNotOfAnyClassIn(Class<?>... types) {3047 return super.isNotOfAnyClassIn(types);3048 }3049 @Override3050 public SELF isNotNull() {3051 return super.isNotNull();3052 }3053 @Override3054 public SELF isNotSameAs(Object other) {3055 return super.isNotSameAs(other);3056 }3057 @Override3058 public SELF isOfAnyClassIn(Class<?>... types) {3059 return super.isOfAnyClassIn(types);3060 }3061 @Override3062 public SELF isSameAs(Object expected) {3063 return super.isSameAs(expected);3064 }3065 @Override3066 public SELF noneMatch(Predicate<? super ELEMENT> predicate) {3067 iterables.assertNoneMatch(info, actual, predicate, PredicateDescription.GIVEN);3068 return myself;3069 }3070 @Override3071 @CheckReturnValue3072 public SELF overridingErrorMessage(String newErrorMessage, Object... args) {3073 return super.overridingErrorMessage(newErrorMessage, args);3074 }3075 @Override3076 @CheckReturnValue3077 public SELF usingDefaultComparator() {3078 return super.usingDefaultComparator();3079 }3080 @Override3081 @CheckReturnValue3082 public SELF usingComparator(Comparator<? super ACTUAL> customComparator) {3083 return usingComparator(customComparator, null);3084 }3085 @Override3086 @CheckReturnValue3087 public SELF usingComparator(Comparator<? super ACTUAL> customComparator, String customComparatorDescription) {3088 return super.usingComparator(customComparator, customComparatorDescription);3089 }3090 @Override3091 @CheckReturnValue3092 public SELF withFailMessage(String newErrorMessage, Object... args) {3093 return super.withFailMessage(newErrorMessage, args);3094 }3095 @Override3096 @CheckReturnValue3097 public SELF withThreadDumpOnError() {3098 return super.withThreadDumpOnError();3099 }3100 /**3101 * Returns an {@code Assert} object that allows performing assertions on the size of the {@link Iterable} under test.3102 * <p>3103 * Once this method is called, the object under test is no longer the {@link Iterable} but its size,3104 * to perform assertions on the {@link Iterable}, call {@link AbstractIterableSizeAssert#returnToIterable()}.3105 * <p>3106 * Example:3107 * <pre><code class='java'> Iterable&lt;Ring&gt; elvesRings = newArrayList(vilya, nenya, narya);3108 *3109 * // assertion will pass:3110 * assertThat(elvesRings).size().isGreaterThan(1)3111 * .isLessThanOrEqualTo(3)3112 * .returnToIterable().contains(narya)3113 * .doesNotContain(oneRing);3114 *3115 * // assertion will fail:3116 * assertThat(elvesRings).size().isGreaterThan(3);</code></pre>3117 *3118 * @return AbstractIterableSizeAssert built with the {@code Iterable}'s size.3119 * @throws NullPointerException if the given {@code Iterable} is {@code null}.3120 */3121 @SuppressWarnings({ "rawtypes", "unchecked" })3122 @CheckReturnValue3123 public AbstractIterableSizeAssert<SELF, ACTUAL, ELEMENT, ELEMENT_ASSERT> size() {3124 requireNonNull(actual, "Can not perform assertions on the size of a null iterable.");3125 return new IterableSizeAssert(this, IterableUtil.sizeOf(actual));3126 }3127 // lazy init TypeComparators3128 protected TypeComparators getComparatorsByType() {3129 if (comparatorsByType == null) comparatorsByType = defaultTypeComparators();3130 return comparatorsByType;3131 }3132 // lazy init TypeComparators3133 protected TypeComparators getComparatorsForElementPropertyOrFieldTypes() {3134 if (comparatorsForElementPropertyOrFieldTypes == null) comparatorsForElementPropertyOrFieldTypes = defaultTypeComparators();3135 return comparatorsForElementPropertyOrFieldTypes;3136 }3137 // use to build the assert instance with a filtered iterable3138 protected abstract SELF newAbstractIterableAssert(Iterable<? extends ELEMENT> iterable);3139 @SuppressWarnings({ "rawtypes", "unchecked" })3140 @Override3141 SELF withAssertionState(AbstractAssert assertInstance) {3142 if (assertInstance instanceof AbstractIterableAssert) {...

Full Screen

Full Screen

getComparatorsByType

Using AI Code Generation

copy

Full Screen

1public class AssertJTest {2 public void test() {3 List<String> list = Arrays.asList("a", "b", "c", "d", "e", "f");4 assertThat(list).getComparatorsByType().hasSize(1);5 }6}7import static org.assertj.core.api.Assertions.assertThat;8import static org.assertj.core.api.Assertions.assertThatExceptionOfType;9import java.util.Arrays;10import java.util.Comparator;11import java.util.List;12import org.junit.Test;13public class AssertJTest {14 public void test() {15 List<String> list = Arrays.asList("a", "b", "c", "d", "e", "f");16 Comparator<String> comparator = assertThat(list).getComparatorsByType().element(0);17 list.sort(comparator);18 assertThat(list).containsExactly("f", "e", "d", "c", "b", "a");19 }20}21import static org.assertj.core.api.Assertions.assertThat;22import static org.assertj.core.api.Assertions.assertThatExceptionOfType;23import java.util.Arrays;24import java.util.Comparator;25import java.util.List;26import org.junit.Test;27public class AssertJTest {28 public void test() {29 List<String> list = Arrays.asList("a", "b", "c", "d", "e", "f");30 Comparator<String> comparator = assertThat(list).getComparatorsByType().element(0);31 assertThat(list).isSortedAccordingTo(comparator);

Full Screen

Full Screen

getComparatorsByType

Using AI Code Generation

copy

Full Screen

1import static org.assertj.core.api.Assertions.assertThat;2import java.util.Comparator;3import java.util.List;4import java.util.stream.Collectors;5import java.util.stream.Stream;6public class AbstractIterableAssert_getComparatorsByType {7 public static void main(String[] args) {8 List<Comparator<String>> comparators = Stream.of(String::compareToIgnoreCase, String::compareTo).collect(Collectors.toList());9 List<Comparator<String>> result = assertThat(comparators).getComparatorsByType(String.CASE_INSENSITIVE_ORDER.getClass());10 assertThat(result).containsExactly(String::compareToIgnoreCase);11 }12}

Full Screen

Full Screen

getComparatorsByType

Using AI Code Generation

copy

Full Screen

1import static org.assertj.core.api.Assertions.assertThat;2import static org.assertj.core.api.Assertions.entry;3import java.util.Comparator;4import java.util.Map;5import org.junit.Test;6public class IterableAssert_getComparatorsByType_Test {7 public void should_return_the_comparator_for_the_given_type() {8 Comparator<Map.Entry<String, String>> comparator = Comparator.comparing(Map.Entry::getKey);9 Iterable<Map.Entry<String, String>> entries = entry("name", "Yoda"), entry("color", "green");10 assertThat(entries).usingComparatorForElementFieldsWithNames(comparator, "name")11 .contains(entry("name", "Yoda"));12 assertThat(entries).usingComparatorForElementFieldsWithNames(comparator, "color")13 .contains(entry("color", "green"));14 assertThat(entries).usingComparatorForElementFieldsWithNames(comparator, "name")15 .usingComparatorForElementFieldsWithNames(comparator, "color")16 .contains(entry("name", "Yoda"), entry("color", "green"));17 }18}

Full Screen

Full Screen

getComparatorsByType

Using AI Code Generation

copy

Full Screen

1public void getComparatorsByType() {2 List<Comparator<?>> comparators = assertThat(new ArrayList<>()).getComparatorsByType(String.class);3 assertThat(comparators).hasSize(1);4}5public void getComparatorsByType() {6 List<Comparator<?>> comparators = assertThat(new ArrayList<>()).getComparatorsByType(String.class);7 assertThat(comparators).hasSize(1);8}9public void getComparatorsByType() {10 List<Comparator<?>> comparators = assertThat(new ArrayList<>()).getComparatorsByType(String.class);11 assertThat(comparators).hasSize(1);12}13public void getComparatorsByType() {14 List<Comparator<?>> comparators = assertThat(new ArrayList<>()).getComparatorsByType(String.class);15 assertThat(comparators).hasSize(1);16}17public void getComparatorsByType() {18 List<Comparator<?>> comparators = assertThat(new ArrayList<>()).getComparatorsByType(String.class);19 assertThat(comparators).hasSize(1);20}21public void getComparatorsByType() {22 List<Comparator<?>> comparators = assertThat(new ArrayList<>()).getComparatorsByType(String.class);23 assertThat(comparators).hasSize(1);24}25public void getComparatorsByType() {26 List<Comparator<?>> comparators = assertThat(new ArrayList<>

Full Screen

Full Screen

getComparatorsByType

Using AI Code Generation

copy

Full Screen

1import org.assertj.core.api.AbstractIterableAssert;2import org.assertj.core.api.Assertions;3import org.assertj.core.api.ListAssert;4import org.assertj.core.api.ListAssertBaseTest;5import org.assertj.core.internal.ComparatorBasedComparisonStrategy;6import org.assertj.core.internal.Comparators;7import org.assertj.core.internal.Iterables;8import org.assertj.core.internal.Objects;9import org.assertj.core.util.introspection.IntrospectionError;10import org.junit.Test;11import java.util.Comparator;12import java.util.List;13import static org.assertj.core.api.Assertions.assertThat;14import static org.assertj.core.api.Assertions.assertThatExceptionOfType;15import static org.assertj.core.test.ExpectedException.none;16import static org.assertj.core.util.Lists.newArrayList;17import static org.mockito.Mockito.*;18public class AbstractIterableAssert_getComparatorsByType_Test extends ListAssertBaseTest {19 private final Comparator<Integer> comparator = (i1, i2) -> i1 - i2;20 protected ListAssert<Integer> invoke_api_method() {21 return assertions.getComparatorsByType(Comparator.class);22 }23 protected void verify_internal_effects() {24 assertThat(getComparators(assertions).getComparatorsByType(Comparator.class)).containsExactly(comparator);25 }26 protected void verify_no_internal_effects() {27 }28 public void should_return_list_assert() {29 assertThat(assertions.getComparatorsByType(Comparator.class)).isInstanceOf(ListAssert.class);30 }31 public void should_return_empty_list_when_no_comparator_of_given_type() {32 assertThat(assertions.getComparatorsByType(String.class)).isEmpty();33 }34 public void should_return_empty_list_when_no_comparator() {35 assertThat(new ListAssert<>(newArrayList())).isEmpty();36 }37}38import org.assertj.core.api.AbstractIterableAssert;39import org.assertj.core.api.Assertions;40import org.assertj.core.api.ListAssert;41import org.assertj.core.api.ListAssertBaseTest;42import org.assertj.core.internal.ComparatorBasedComparisonStrategy;43import org.assertj.core.internal.Comparators;44import org.assertj.core.internal.Iterables;45import org.assertj.core.internal.Objects;46import org.junit.Test;47import java.util.Comparator;48import java.util

Full Screen

Full Screen

getComparatorsByType

Using AI Code Generation

copy

Full Screen

1import org.assertj.core.api.Assertions;2import org.assertj.core.api.ComparableAssert;3import org.assertj.core.api.Condition;4import org.assertj.core.api.ListAssert;5import org.assertj.core.api.ObjectAssert;6import org.assertj.core.api.ObjectArrayAssert;7import org.assertj.core.api.StringAssert;8import org.assertj.core.api.filter.Filters;9import org.assertj.core.api.filter.InFilter;10import org.assertj.core.api.filter.NotFilter;11import org.assertj.core.api.filter.OutFilter;12import org.assertj.core.api.filter.RegexFilter;13import org.assertj.core.api.iterable.Extractor;14import org.assertj.core.api.iterable.ThrowingExtractor;15import org.assertj.core.api.recursive.comparison.RecursiveComparisonConfiguration;16import java.util.Comparator;17import java.util.List;18import java.util.function.BiPredicate;19import java.util.function.Consumer;20import java.util.function.Function;21import java.util.function.Predicate;22public class AssertJGetComparatorsByType {23 public static void main(String[] args) {24 String[] array1 = {"one", "two", "three", "four", "five"};25 String[] array2 = {"one", "two", "three", "four", "five"};26 Comparator<String>[] comparators = Assertions.assertThat(array1).getComparatorsByType();

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