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

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

Source:AbstractIterableAssert.java Github

copy

Full Screen

...873 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) {...

Full Screen

Full Screen

newListAssertInstanceForMethodsChangingElementType

Using AI Code Generation

copy

Full Screen

1import org.assertj.core.api.Assertions;2import org.junit.jupiter.api.Test;3import java.util.ArrayList;4import java.util.List;5public class AssertJTest {6 public void testAssertJ() {7 List<String> list = new ArrayList<>();8 list.add("One");9 list.add("Two");10 list.add("Three");11 Assertions.assertThat(list).newListAssertInstanceForMethodsChangingElementType()12 .contains("One")13 .contains("Two")14 .contains("Three");15 }16}17at org.junit.platform.launcher.core.DefaultLauncher.discoverEngineRoot(DefaultLauncher.java:126)18at org.junit.platform.launcher.core.DefaultLauncher.discoverRoot(DefaultLauncher.java:113)19at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:84)20at org.junit.platform.console.tasks.DiscoveryTask.execute(DiscoveryTask.java:47)21at org.junit.platform.console.tasks.ConsoleTask.execute(ConsoleTask.java:42)22at org.junit.platform.console.ConsoleLauncher.executeTasks(ConsoleLauncher.java:51)23at org.junit.platform.console.ConsoleLauncher.execute(ConsoleLauncher.java:40)24at org.junit.platform.console.ConsoleLauncher.main(ConsoleLauncher.java:25)25at org.junit.platform.launcher.core.DefaultLauncher.discoverEngineRoot(DefaultLauncher.java:126)26at org.junit.platform.launcher.core.DefaultLauncher.discoverRoot(DefaultLauncher.java:113)27at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:84)28at org.junit.platform.console.tasks.DiscoveryTask.execute(DiscoveryTask.java:47)29at org.junit.platform.console.tasks.ConsoleTask.execute(ConsoleTask.java:42)30at org.junit.platform.console.ConsoleLauncher.executeTasks(ConsoleLauncher.java:51)31at org.junit.platform.console.ConsoleLauncher.execute(ConsoleLauncher.java:40)32at org.junit.platform.console.ConsoleLauncher.main(ConsoleLauncher.java:25)33at java.lang.Class.forName0(Native Method)34at java.lang.Class.forName(Class.java:348)35at org.junit.platform.commons.util.ReflectionUtils.tryToLoadClass(ReflectionUtils.java:510)36at org.junit.platform.commons.util.ReflectionUtils.tryToLoadClass(ReflectionUtils.java:500)

Full Screen

Full Screen

newListAssertInstanceForMethodsChangingElementType

Using AI Code Generation

copy

Full Screen

1assertThat(newList).newListAssertInstanceForMethodsChangingElementType()2 .containsExactly(1, 2, 3)3 .contains(1, atIndex(0))4 .contains(2, atIndex(1))5 .contains(3, atIndex(2));6assertThat(newList).newListAssertInstanceForMethodsChangingElementType()7 .containsExactly(1, 2, 3)8 .contains(1, atIndex(0))9 .contains(2, atIndex(1))10 .contains(3, atIndex(2));11assertThat(newList).newListAssertInstanceForMethodsChangingElementType()12 .containsExactly(1, 2, 3)13 .contains(1, atIndex(0))14 .contains(2, atIndex(1))15 .contains(3, atIndex(2));16assertThat(newList).newListAssertInstanceForMethodsChangingElementType()17 .containsExactly(1, 2, 3)18 .contains(1, atIndex(0))19 .contains(2, atIndex(1))20 .contains(3, atIndex(2));21assertThat(newList).newListAssertInstanceForMethodsChangingElementType()22 .containsExactly(1, 2, 3)23 .contains(1, atIndex(0))24 .contains(2, atIndex(1))25 .contains(3, atIndex(2));26assertThat(newList).newListAssertInstanceForMethodsChangingElementType()27 .containsExactly(1, 2, 3)28 .contains(1, atIndex(0))29 .contains(2, atIndex(1))30 .contains(3, atIndex(2));31assertThat(newList).newListAssertInstanceForMethodsChangingElementType()32 .containsExactly(1, 2

Full Screen

Full Screen

newListAssertInstanceForMethodsChangingElementType

Using AI Code Generation

copy

Full Screen

1import org.assertj.core.api.IterableAssert;2import org.assertj.core.api.ListAssert;3import org.assertj.core.api.ListAssertBaseTest;4import org.assertj.core.util.introspection.IntrospectionError;5import org.junit.jupiter.api.DisplayName;6import org.junit.jupiter.api.Test;7import java.util.List;8import static org.assertj.core.api.Assertions.assertThat;9import static org.assertj.core.api.Assertions.assertThatExceptionOfType;10import static org.assertj.core.util.Lists.list;11@DisplayName("IterableAssert newListAssertInstanceForMethodsChangingElementType method")12class IterableAssert_newListAssertInstanceForMethodsChangingElementType_Test extends ListAssertBaseTest {13 void should_create_new_ListAssert_with_different_element_type() {14 Iterable<String> stringList = list("Yoda", "Luke");15 ListAssert<Integer> listAssert = new IterableAssert<>(stringList)16 .newListAssertInstanceForMethodsChangingElementType(Integer.class);17 assertThat(listAssert).isNotNull();18 }19 void should_fail_if_element_type_is_not_assignable_from_given_type() {20 Iterable<String> stringList = list("Yoda", "Luke");21 assertThatExceptionOfType(IntrospectionError.class).isThrownBy(() -> new IterableAssert<>(stringList)22 .newListAssertInstanceForMethodsChangingElementType(List.class));23 }24}25import org.assertj.core.api.ListAssert;26import org.assertj.core.api.ListAssertBaseTest;27import org.assertj.core.util.introspection.IntrospectionError;28import org.junit.jupiter.api.DisplayName;29import org.junit.jupiter.api.Test;30import java.util.List;31import static org.assertj.core.api.Assertions.assertThat;32import static org.assertj.core.api.Assertions.assertThatExceptionOfType;33import static org.assertj.core.util.Lists.list;34@DisplayName("ListAssert newListAssertInstanceForMethodsChangingElementType method")35class ListAssert_newListAssertInstanceForMethodsChangingElementType_Test extends ListAssertBaseTest {36 void should_create_new_ListAssert_with_different_element_type() {37 List<String> stringList = list("Yoda", "Luke");38 ListAssert<Integer> listAssert = new ListAssert<>(stringList)

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