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

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

Source:AbstractIterableAssert.java Github

copy

Full Screen

...1713 * @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) {3143 AbstractIterableAssert iterableAssert = (AbstractIterableAssert) assertInstance;3144 return (SELF) super.withAssertionState(assertInstance).withIterables(iterableAssert.iterables)3145 .withTypeComparators(iterableAssert.comparatorsByType)3146 .withComparatorsForElementPropertyOrFieldNames(iterableAssert.comparatorsForElementPropertyOrFieldNames)3147 .withComparatorsForElementPropertyOrFieldTypes(iterableAssert.comparatorsForElementPropertyOrFieldTypes);...

Full Screen

Full Screen

Source:AbstractObjectArrayAssert.java Github

copy

Full Screen

...1672 * @since 2.5.0 / 3.5.01673 */1674 @CheckReturnValue1675 public <C> SELF usingComparatorForElementFieldsWithType(Comparator<C> comparator, Class<C> type) {1676 getComparatorsForElementPropertyOrFieldTypes().put(type, comparator);1677 return myself;1678 }1679 /**1680 * Allows to set a specific comparator for the given type of elements or their fields.1681 * Extends {@link #usingComparatorForElementFieldsWithType} by applying comparator specified for given type1682 * to elements themselves, not only to their fields.1683 * <p>1684 * Usage of this method affects comparators set by the following methods:1685 * <ul>1686 * <li>{@link #usingFieldByFieldElementComparator}</li>1687 * <li>{@link #usingElementComparatorOnFields}</li>1688 * <li>{@link #usingElementComparatorIgnoringFields}</li>1689 * <li>{@link #usingRecursiveFieldByFieldElementComparator}</li>1690 * </ul>1691 * <p>1692 * Example:1693 * <pre><code class='java'> Person obiwan = new Person("Obi-Wan");1694 * obiwan.setHeight(new BigDecimal("1.820"));1695 *1696 * // assertion will pass1697 * assertThat(obiwan).extracting("name", "height")1698 * .usingComparatorForType(BIG_DECIMAL_COMPARATOR, BigDecimal.class)1699 * .containsExactly("Obi-Wan", new BigDecimal("1.82"));</code></pre>1700 *1701 * @param <C> the type of elements to compare.1702 * @param comparator the {@link java.util.Comparator} to use1703 * @param type the {@link java.lang.Class} of the type of the element or element fields the comparator should be used for1704 * @return {@code this} assertions object1705 * @since 2.9.0 / 3.9.01706 */1707 @CheckReturnValue1708 public <C> SELF usingComparatorForType(Comparator<C> comparator, Class<C> type) {1709 if (arrays.getComparator() == null) {1710 usingElementComparator(new ExtendedByTypesComparator(getComparatorsByType()));1711 }1712 getComparatorsForElementPropertyOrFieldTypes().put(type, comparator);1713 getComparatorsByType().put(type, comparator);1714 return myself;1715 }1716 /**1717 * Use field/property by field/property comparison (including inherited fields/properties) instead of relying on1718 * actual type A <code>equals</code> method to compare group elements for incoming assertion checks. Private fields1719 * are included but this can be disabled using {@link Assertions#setAllowExtractingPrivateFields(boolean)}.1720 * <p>1721 * This can be handy if <code>equals</code> method of the objects to compare does not suit you.1722 * <p>1723 * You can specify a custom comparator per name or type of element field with1724 * {@link #usingComparatorForElementFieldsWithNames(Comparator, String...)}1725 * and {@link #usingComparatorForElementFieldsWithType(Comparator, Class)}.1726 * <p>1727 * Note that the comparison is <b>not</b> recursive, if one of the fields/properties is an Object, it will be compared1728 * to the other field/property using its <code>equals</code> method.1729 * <p>1730 * Example:1731 * <pre><code class='java'> TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT);1732 * TolkienCharacter frodoClone = new TolkienCharacter("Frodo", 33, HOBBIT);1733 *1734 * // Fail if equals has not been overridden in TolkienCharacter as equals default implementation only compares references1735 * assertThat(array(frodo)).contains(frodoClone);1736 *1737 * // frodo and frodoClone are equals when doing a field by field comparison.1738 * assertThat(array(frodo)).usingFieldByFieldElementComparator().contains(frodoClone);</code></pre>1739 *1740 * @return {@code this} assertion object.1741 */1742 @CheckReturnValue1743 public SELF usingFieldByFieldElementComparator() {1744 return usingExtendedByTypesElementComparator(new FieldByFieldComparator(comparatorsForElementPropertyOrFieldNames,1745 getComparatorsForElementPropertyOrFieldTypes()));1746 }1747 /**1748 * Use a recursive field/property by field/property comparison (including inherited fields/properties)1749 * instead of relying on actual type A <code>equals</code> method to compare group elements for incoming1750 * assertion checks. This can be useful if actual's {@code equals} implementation does not suit you.1751 * <p>1752 * The recursive property/field comparison is <b>not</b> applied on fields having a custom {@code equals}1753 * implementation, i.e. the overridden {@code equals} method will be used instead of a field/property by field/property comparison.1754 * <p>1755 * You can specify a custom comparator per (nested) name or type of element field with1756 * {@link #usingComparatorForElementFieldsWithNames(Comparator, String...) usingComparatorForElementFieldsWithNames}1757 * and {@link #usingComparatorForElementFieldsWithType(Comparator, Class) usingComparatorForElementFieldsWithType}.1758 * <p>1759 * The recursive comparison handles cycles.1760 * <p>1761 * The objects to compare can be of different types but must have the same properties/fields. For example if actual object has a1762 * {@code name} String field, the other object must also have one.1763 * <p>1764 * If an object has a field and a property with the same name, the property value will be used over the field.1765 * <p>1766 * Example:1767 *1768 * <pre><code class='java'> TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT);1769 * TolkienCharacter pippin = new TolkienCharacter("Pippin", 28, HOBBIT);1770 * frodo.setFriend(pippin);1771 * pippin.setFriend(frodo);1772 *1773 * TolkienCharacter frodoClone = new TolkienCharacter("Frodo", 33, HOBBIT);1774 * TolkienCharacter pippinClone = new TolkienCharacter("Pippin", 28, HOBBIT);1775 * frodoClone.setFriend(pippinClone);1776 * pippinClone.setFriend(frodoClone);1777 *1778 * TolkienCharacter[] hobbits = new TolkienCharacter[] {frodo, pippin};1779 *1780 * // fails if equals has not been overridden in TolkienCharacter as it would compares object references1781 * assertThat(hobbits).contains(frodoClone, pippinClone);1782 *1783 * // frodo/frodoClone and pippin/pippinClone are equals when doing a recursive property/field by property/field comparison1784 * assertThat(hobbits).usingRecursiveFieldByFieldElementComparator()1785 * .contains(frodoClone, pippinClone);</code></pre>1786 *1787 * @return {@code this} assertion object.1788 * @since 2.5.0 / 3.5.01789 */1790 @CheckReturnValue1791 public SELF usingRecursiveFieldByFieldElementComparator() {1792 return usingExtendedByTypesElementComparator(new RecursiveFieldByFieldComparator(comparatorsForElementPropertyOrFieldNames,1793 getComparatorsForElementPropertyOrFieldTypes()));1794 }1795 /**1796 * Use field/property by field/property comparison on the <b>given fields/properties only</b> (including inherited1797 * fields/properties) instead of relying on actual type A <code>equals</code> method to compare group elements for1798 * incoming assertion checks. Private fields are included but this can be disabled using1799 * {@link Assertions#setAllowExtractingPrivateFields(boolean)}.1800 * <p>1801 * This can be handy if <code>equals</code> method of the objects to compare does not suit you.1802 * <p>1803 * You can specify a custom comparator per name or type of element field with1804 * {@link #usingComparatorForElementFieldsWithNames(Comparator, String...)}1805 * and {@link #usingComparatorForElementFieldsWithType(Comparator, Class)}.1806 * <p>1807 * Note that the comparison is <b>not</b> recursive, if one of the fields/properties is an Object, it will be compared1808 * to the other field/property using its <code>equals</code> method.1809 * <p>1810 * Example:1811 * <pre><code class='java'> TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT);1812 * TolkienCharacter sam = new TolkienCharacter("Sam", 38, HOBBIT);1813 *1814 * // frodo and sam both are hobbits, so they are equals when comparing only race1815 * assertThat(array(frodo)).usingElementComparatorOnFields("race").contains(sam); // OK1816 *1817 * // ... but not when comparing both name and race1818 * assertThat(array(frodo)).usingElementComparatorOnFields("name", "race").contains(sam); // FAIL</code></pre>1819 *1820 * @param fields the name of the fields to use the element comparator on1821 * @return {@code this} assertion object.1822 */1823 @CheckReturnValue1824 public SELF usingElementComparatorOnFields(String... fields) {1825 return usingExtendedByTypesElementComparator(new OnFieldsComparator(comparatorsForElementPropertyOrFieldNames,1826 getComparatorsForElementPropertyOrFieldTypes(),1827 fields));1828 }1829 /**1830 * Use field/property by field/property on all fields/properties <b>except</b> the given ones (including inherited1831 * fields/properties) instead of relying on actual type A <code>equals</code> method to compare group elements for1832 * incoming assertion checks. Private fields are included but this can be disabled using1833 * {@link Assertions#setAllowExtractingPrivateFields(boolean)}.1834 * <p>1835 * This can be handy if <code>equals</code> method of the objects to compare does not suit you.1836 * <p>1837 * You can specify a custom comparator per name or type of element field with1838 * {@link #usingComparatorForElementFieldsWithNames(Comparator, String...)}1839 * and {@link #usingComparatorForElementFieldsWithType(Comparator, Class)}.1840 * <p>1841 * Note that the comparison is <b>not</b> recursive, if one of the fields/properties is an Object, it will be compared1842 * to the other field/property using its <code>equals</code> method.1843 * <p>1844 * Example:1845 * <pre><code class='java'> TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT);1846 * TolkienCharacter sam = new TolkienCharacter("Sam", 38, HOBBIT);1847 *1848 * // frodo and sam both are hobbits, so they are equals when comparing only race (i.e. ignoring all other fields)1849 * assertThat(array(frodo)).usingElementComparatorIgnoringFields("name", "age").contains(sam); // OK1850 *1851 * // ... but not when comparing both name and race1852 * assertThat(array(frodo)).usingElementComparatorIgnoringFields("age").contains(sam); // FAIL</code></pre>1853 *1854 * @param fields the name of the fields to ignore1855 * @return {@code this} assertion object.1856 */1857 @CheckReturnValue1858 public SELF usingElementComparatorIgnoringFields(String... fields) {1859 return usingExtendedByTypesElementComparator(new IgnoringFieldsComparator(comparatorsForElementPropertyOrFieldNames,1860 getComparatorsForElementPropertyOrFieldTypes(),1861 fields));1862 }1863 /**1864 * Extract the values of given field or property from the array's elements under test into a new list, this new list1865 * becoming the object under test.1866 * <p>1867 * It allows you to test a field/property of the array's elements instead of testing the elements themselves, which can1868 * be much less work !1869 * <p>1870 * Let's take an example to make things clearer :1871 * <pre><code class='java'> // Build a array of TolkienCharacter, a TolkienCharacter has a name (String) and a Race (a class)1872 * // they can be public field or properties, both works when extracting their values.1873 * TolkienCharacter[] fellowshipOfTheRing = new TolkienCharacter[] {1874 * new TolkienCharacter(&quot;Frodo&quot;, 33, HOBBIT),1875 * new TolkienCharacter(&quot;Sam&quot;, 38, HOBBIT),1876 * new TolkienCharacter(&quot;Gandalf&quot;, 2020, MAIA),1877 * new TolkienCharacter(&quot;Legolas&quot;, 1000, ELF),1878 * new TolkienCharacter(&quot;Pippin&quot;, 28, HOBBIT),1879 * new TolkienCharacter(&quot;Gimli&quot;, 139, DWARF),1880 * new TolkienCharacter(&quot;Aragorn&quot;, 87, MAN,1881 * new TolkienCharacter(&quot;Boromir&quot;, 37, MAN)1882 * };1883 *1884 * // let's verify the names of TolkienCharacter in fellowshipOfTheRing :1885 *1886 * assertThat(fellowshipOfTheRing).extracting(&quot;name&quot;)1887 * .contains(&quot;Boromir&quot;, &quot;Gandalf&quot;, &quot;Frodo&quot;)1888 * .doesNotContain(&quot;Sauron&quot;, &quot;Elrond&quot;);1889 *1890 * // you can also extract nested field/property like the name of Race :1891 *1892 * assertThat(fellowshipOfTheRing).extracting(&quot;race.name&quot;)1893 * .contains(&quot;Hobbit&quot;, &quot;Elf&quot;)1894 * .doesNotContain(&quot;Orc&quot;);</code></pre>1895 *1896 * A property with the given name is looked for first, if it does not exist then a field with the given name1897 * is looked for.1898 * <p>1899 * Note that the order of extracted field/property values is consistent with the array order.1900 *1901 * @param fieldOrProperty the field/property to extract from the array under test1902 * @return a new assertion object whose object under test is the list of extracted field/property values.1903 * @throws IntrospectionError if no field or property exists with the given name1904 */1905 @CheckReturnValue1906 public AbstractListAssert<?, List<? extends Object>, Object, ObjectAssert<Object>> extracting(String fieldOrProperty) {1907 Object[] values = FieldsOrPropertiesExtractor.extract(actual, byName(fieldOrProperty));1908 String extractedDescription = extractedDescriptionOf(fieldOrProperty);1909 String description = mostRelevantDescription(info.description(), extractedDescription);1910 return newListAssertInstance(newArrayList(values)).withAssertionState(myself).as(description);1911 }1912 /**1913 * Extract the values of given field or property from the array's elements under test into a new list, this new list of the provided type1914 * becoming the object under test.1915 * <p>1916 * It allows you to test a field/property of the array's elements instead of testing the elements themselves, which can1917 * be much less work !1918 * <p>1919 * Let's take an example to make things clearer :1920 * <pre><code class='java'> // Build an array of TolkienCharacter, a TolkienCharacter has a name (String) and a Race (a class)1921 * // they can be public field or properties, both works when extracting their values.1922 * TolkienCharacter[] fellowshipOfTheRing = new TolkienCharacter[] {1923 * new TolkienCharacter(&quot;Frodo&quot;, 33, HOBBIT),1924 * new TolkienCharacter(&quot;Sam&quot;, 38, HOBBIT),1925 * new TolkienCharacter(&quot;Gandalf&quot;, 2020, MAIA),1926 * new TolkienCharacter(&quot;Legolas&quot;, 1000, ELF),1927 * new TolkienCharacter(&quot;Pippin&quot;, 28, HOBBIT),1928 * new TolkienCharacter(&quot;Gimli&quot;, 139, DWARF),1929 * new TolkienCharacter(&quot;Aragorn&quot;, 87, MAN,1930 * new TolkienCharacter(&quot;Boromir&quot;, 37, MAN)1931 * };1932 *1933 * // let's verify the names of TolkienCharacter in fellowshipOfTheRing :1934 *1935 * assertThat(fellowshipOfTheRing).extracting(&quot;name&quot;, String.class)1936 * .contains(&quot;Boromir&quot;, &quot;Gandalf&quot;, &quot;Frodo&quot;)1937 * .doesNotContain(&quot;Sauron&quot;, &quot;Elrond&quot;);1938 *1939 * // you can also extract nested field/property like the name of Race :1940 *1941 * assertThat(fellowshipOfTheRing).extracting(&quot;race.name&quot;, String.class)1942 * .contains(&quot;Hobbit&quot;, &quot;Elf&quot;)1943 * .doesNotContain(&quot;Orc&quot;);</code></pre>1944 *1945 * A property with the given name is looked for first, if it does not exist then a field with the given name1946 * is looked for.1947 * <p>1948 * Note that the order of extracted field/property values is consistent with the order of the array under test.1949 *1950 * @param <P> the type of elements to extract.1951 * @param fieldOrProperty the field/property to extract from the array under test1952 * @param extractingType type to return1953 * @return a new assertion object whose object under test is the list of extracted field/property values.1954 * @throws IntrospectionError if no field or property exists with the given name1955 */1956 @CheckReturnValue1957 public <P> AbstractListAssert<?, List<? extends P>, P, ObjectAssert<P>> extracting(String fieldOrProperty,1958 Class<P> extractingType) {1959 @SuppressWarnings("unchecked")1960 List<P> values = (List<P>) FieldsOrPropertiesExtractor.extract(Arrays.asList(actual), byName(fieldOrProperty));1961 String extractedDescription = extractedDescriptionOf(fieldOrProperty);1962 String description = mostRelevantDescription(info.description(), extractedDescription);1963 return newListAssertInstance(values).withAssertionState(myself).as(description);1964 }1965 /**1966 * Extract the values of given fields/properties from the array's elements under test into a list composed of1967 * Tuple (a simple data structure), this new list becoming the object under test.1968 * <p>1969 * It allows you to test fields/properties of the array's elements instead of testing the elements themselves, it1970 * can be sometimes much less work !1971 * <p>1972 * The Tuple data corresponds to the extracted values of the given fields/properties, for instance if you ask to1973 * extract "id", "name" and "email" then each Tuple data will be composed of id, name and email extracted from the1974 * element of the initial array (the Tuple's data order is the same as the given fields/properties order).1975 * <p>1976 * Let's take an example to make things clearer :1977 * <pre><code class='java'> // Build an array of TolkienCharacter, a TolkienCharacter has a name (String) and a Race (a class)1978 * // they can be public field or properties, both works when extracting their values.1979 * TolkienCharacter[] fellowshipOfTheRing = new TolkienCharacter[] {1980 * new TolkienCharacter(&quot;Frodo&quot;, 33, HOBBIT),1981 * new TolkienCharacter(&quot;Sam&quot;, 38, HOBBIT),1982 * new TolkienCharacter(&quot;Gandalf&quot;, 2020, MAIA),1983 * new TolkienCharacter(&quot;Legolas&quot;, 1000, ELF),1984 * new TolkienCharacter(&quot;Pippin&quot;, 28, HOBBIT),1985 * new TolkienCharacter(&quot;Gimli&quot;, 139, DWARF),1986 * new TolkienCharacter(&quot;Aragorn&quot;, 87, MAN,1987 * new TolkienCharacter(&quot;Boromir&quot;, 37, MAN)1988 * };1989 *1990 * // let's verify 'name' and 'age' of some TolkienCharacter in fellowshipOfTheRing :1991 *1992 * assertThat(fellowshipOfTheRing).extracting(&quot;name&quot;, &quot;age&quot;)1993 * .contains(tuple(&quot;Boromir&quot;, 37),1994 * tuple(&quot;Sam&quot;, 38),1995 * tuple(&quot;Legolas&quot;, 1000));1996 *1997 *1998 * // extract 'name', 'age' and Race name values.1999 *2000 * assertThat(fellowshipOfTheRing).extracting(&quot;name&quot;, &quot;age&quot;, &quot;race.name&quot;)2001 * .contains(tuple(&quot;Boromir&quot;, 37, &quot;Man&quot;),2002 * tuple(&quot;Sam&quot;, 38, &quot;Hobbit&quot;),2003 * tuple(&quot;Legolas&quot;, 1000, &quot;Elf&quot;));</code></pre>2004 *2005 * A property with the given name is looked for first, if it does not exist the a field with the given name is2006 * looked for.2007 * <p>2008 * Note that the order of extracted property/field values is consistent with the iteration order of the array under2009 * test.2010 *2011 * @param propertiesOrFields the properties/fields to extract from the initial array under test2012 * @return a new assertion object whose object under test is the list of Tuple with extracted properties/fields values as data.2013 * @throws IntrospectionError if one of the given name does not match a field or property in one of the initial Iterable's element.2014 */2015 @CheckReturnValue2016 public AbstractListAssert<?, List<? extends Tuple>, Tuple, ObjectAssert<Tuple>> extracting(String... propertiesOrFields) {2017 List<Tuple> values = FieldsOrPropertiesExtractor.extract(Arrays.asList(actual), byName(propertiesOrFields));2018 String extractedDescription = extractedDescriptionOf(propertiesOrFields);2019 String description = mostRelevantDescription(info.description(), extractedDescription);2020 return newListAssertInstance(values).withAssertionState(myself).as(description);2021 }2022 /**2023 * Extract the values from the array's elements by applying an extracting function on them, the resulting list becomes2024 * the new object under test.2025 * <p>2026 * This method is similar to {@link #extracting(String)} but more refactoring friendly as it does not use introspection.2027 * <p>2028 * Let's take a look an example:2029 * <pre><code class='java'> // Build a list of TolkienCharacter, a TolkienCharacter has a name, and age and a Race (a specific class)2030 * // they can be public field or properties, both can be extracted.2031 * TolkienCharacter[] fellowshipOfTheRing = new TolkienCharacter[] {2032 * new TolkienCharacter(&quot;Frodo&quot;, 33, HOBBIT),2033 * new TolkienCharacter(&quot;Sam&quot;, 38, HOBBIT),2034 * new TolkienCharacter(&quot;Gandalf&quot;, 2020, MAIA),2035 * new TolkienCharacter(&quot;Legolas&quot;, 1000, ELF),2036 * new TolkienCharacter(&quot;Pippin&quot;, 28, HOBBIT),2037 * new TolkienCharacter(&quot;Gimli&quot;, 139, DWARF),2038 * new TolkienCharacter(&quot;Aragorn&quot;, 87, MAN,2039 * new TolkienCharacter(&quot;Boromir&quot;, 37, MAN)2040 * };2041 *2042 * // fellowship has hobbitses, right, my presioussss?2043 * assertThat(fellowshipOfTheRing).extracting(TolkienCharacter::getRace).contains(HOBBIT);</code></pre>2044 *2045 * Note that the order of extracted property/field values is consistent with the iteration order of the Iterable under2046 * test, for example if it's a {@link HashSet}, you won't be able to make any assumptions on the extracted values2047 * order.2048 *2049 * @param <U> the type of elements to extract.2050 * @param extractor the object transforming input object to desired one2051 * @return a new assertion object whose object under test is the list of extracted values.2052 */2053 @CheckReturnValue2054 public <U> AbstractListAssert<?, List<? extends U>, U, ObjectAssert<U>> extracting(Function<? super ELEMENT, U> extractor) {2055 List<U> values = FieldsOrPropertiesExtractor.extract(Arrays.asList(actual), extractor);2056 return newListAssertInstance(values).withAssertionState(myself);2057 }2058 /**2059 * Extract the values from the array's elements by applying an extracting function (which might throw an exception)2060 * on them, the resulting list of extracted values becomes a new object under test.2061 * <p>2062 * Any checked exception raised in the extractor is rethrown wrapped in a {@link RuntimeException}.2063 * <p>2064 * It allows to test values from the elements in safer way than by using {@link #extracting(String)}, as it2065 * doesn't use introspection.2066 * <p>2067 * Let's take a look an example:2068 * <pre><code class='java'> // Build a list of TolkienCharacter, a TolkienCharacter has a name, and age and a Race (a specific class)2069 * // they can be public field or properties, both can be extracted.2070 * TolkienCharacter[] fellowshipOfTheRing = new TolkienCharacter[] {2071 * new TolkienCharacter(&quot;Frodo&quot;, 33, HOBBIT),2072 * new TolkienCharacter(&quot;Sam&quot;, 38, HOBBIT),2073 * new TolkienCharacter(&quot;Gandalf&quot;, 2020, MAIA),2074 * new TolkienCharacter(&quot;Legolas&quot;, 1000, ELF),2075 * new TolkienCharacter(&quot;Pippin&quot;, 28, HOBBIT),2076 * new TolkienCharacter(&quot;Gimli&quot;, 139, DWARF),2077 * new TolkienCharacter(&quot;Aragorn&quot;, 87, MAN,2078 * new TolkienCharacter(&quot;Boromir&quot;, 37, MAN)2079 * };2080 *2081 * assertThat(fellowshipOfTheRing).extracting(input -&gt; {2082 * if (input.getAge() &lt; 20) {2083 * throw new Exception("age &lt; 20");2084 * }2085 * return input.getName();2086 * }).contains("Frodo");</code></pre>2087 * <p>2088 * Note that the order of extracted property/field values is consistent with the iteration order of the array under test.2089 *2090 * @param <V> the type of elements to extract.2091 * @param <EXCEPTION> the exception type of {@link ThrowingExtractor}2092 * @param extractor the object transforming input object to desired one2093 * @return a new assertion object whose object under test is the list of extracted values2094 * @since 3.7.02095 */2096 @CheckReturnValue2097 public <V, EXCEPTION extends Exception> AbstractListAssert<?, List<? extends V>, V, ObjectAssert<V>> extracting(ThrowingExtractor<? super ELEMENT, V, EXCEPTION> extractor) {2098 List<V> values = FieldsOrPropertiesExtractor.extract(newArrayList(actual), extractor);2099 return newListAssertInstance(values).withAssertionState(myself);2100 }2101 /**2102 * Use the given {@link Function}s to extract the values from the array's elements into a new list2103 * composed of {@link Tuple}s (a simple data structure containing the extracted values), this new list becoming the2104 * object under test.2105 * <p>2106 * It allows you to test values from the array's elements instead of testing the elements themselves, which sometimes can be2107 * much less work!2108 * <p>2109 * The {@link Tuple} data corresponds to the extracted values from the arrays's elements, for instance if you pass functions2110 * extracting "id", "name" and "email" values then each {@link Tuple}'s data will be composed of an id, a name and an email2111 * extracted from the element of the initial array (the Tuple's data order is the same as the given functions order).2112 * <p>2113 * Let's take a look at an example to make things clearer :2114 * <pre><code class='java'> // Build an array of TolkienCharacter, a TolkienCharacter has a name (String) and a Race (a class)2115 * // they can be public field or properties, both works when extracting their values.2116 * TolkienCharacter[] fellowshipOfTheRing = new TolkienCharacter[] {2117 * new TolkienCharacter(&quot;Frodo&quot;, 33, HOBBIT),2118 * new TolkienCharacter(&quot;Sam&quot;, 38, HOBBIT),2119 * new TolkienCharacter(&quot;Gandalf&quot;, 2020, MAIA),2120 * new TolkienCharacter(&quot;Legolas&quot;, 1000, ELF),2121 * new TolkienCharacter(&quot;Pippin&quot;, 28, HOBBIT),2122 * new TolkienCharacter(&quot;Gimli&quot;, 139, DWARF),2123 * new TolkienCharacter(&quot;Aragorn&quot;, 87, MAN,2124 * new TolkienCharacter(&quot;Boromir&quot;, 37, MAN)2125 * };2126 *2127 * // let's verify 'name', 'age' and Race of some TolkienCharacter in fellowshipOfTheRing :2128 * assertThat(fellowshipOfTheRing).extracting(TolkienCharacter::getName,2129 * character -&gt; character.getAge(),2130 * TolkienCharacter::getRace)2131 * .containsOnly(tuple(&quot;Frodo&quot;, 33, HOBBIT),2132 * tuple(&quot;Sam&quot;, 38, HOBBIT),2133 * tuple(&quot;Gandalf&quot;, 2020, MAIA),2134 * tuple(&quot;Legolas&quot;, 1000, ELF),2135 * tuple(&quot;Pippin&quot;, 28, HOBBIT),2136 * tuple(&quot;Gimli&quot;, 139, DWARF),2137 * tuple(&quot;Aragorn&quot;, 87, MAN),2138 * tuple(&quot;Boromir&quot;, 37, MAN));</code></pre>2139 * You can use lambda expression or a method reference to extract the expected values.2140 * <p>2141 * Use {@link Tuple#tuple(Object...)} to initialize the expected values.2142 * <p>2143 * Note that the order of the extracted tuples list is consistent with the iteration order of the array under test,2144 * for example if it's a {@link HashSet}, you won't be able to make any assumptions on the extracted tuples order.2145 *2146 * @param extractors the extractor functions to extract a value from an element of the array under test.2147 * @return a new assertion object whose object under test is the list of Tuples containing the extracted values.2148 */2149 @CheckReturnValue2150 public AbstractListAssert<?, List<? extends Tuple>, Tuple, ObjectAssert<Tuple>> extracting(@SuppressWarnings("unchecked") Function<? super ELEMENT, ?>... extractors) {2151 Function<ELEMENT, Tuple> tupleExtractor = objectToExtractValueFrom -> new Tuple(Stream.of(extractors)2152 .map(extractor -> extractor.apply(objectToExtractValueFrom))2153 .toArray());2154 List<Tuple> tuples = stream(actual).map(tupleExtractor).collect(toList());2155 return newListAssertInstance(tuples).withAssertionState(myself);2156 }2157 /**2158 * Extract the Iterable values from arrays elements under test by applying an Iterable extracting function on them2159 * and concatenating the result lists into an array which becomes the new object under test.2160 * <p>2161 * It allows testing the results of extracting values that are represented by Iterables.2162 * <p>2163 * For example:2164 * <pre><code class='java'> CartoonCharacter bart = new CartoonCharacter("Bart Simpson");2165 * CartoonCharacter lisa = new CartoonCharacter("Lisa Simpson");2166 * CartoonCharacter maggie = new CartoonCharacter("Maggie Simpson");2167 * CartoonCharacter homer = new CartoonCharacter("Homer Simpson");2168 * homer.addChildren(bart, lisa, maggie);2169 *2170 * CartoonCharacter pebbles = new CartoonCharacter("Pebbles Flintstone");2171 * CartoonCharacter fred = new CartoonCharacter("Fred Flintstone");2172 * fred.getChildren().add(pebbles);2173 *2174 * CartoonCharacter[] parents = new CartoonCharacter[] { homer, fred };2175 * // check children2176 * assertThat(parents).flatExtracting(CartoonCharacter::getChildren)2177 * .containsOnly(bart, lisa, maggie, pebbles);</code></pre>2178 *2179 * The order of extracted values is consisted with both the order of the collection itself, as well as the extracted2180 * collections.2181 *2182 * @param <V> the type of elements to extract.2183 * @param <C> the type of collection to flat/extract.2184 * @param extractor the object transforming input object to an Iterable of desired ones2185 * @return a new assertion object whose object under test is the list of values extracted2186 */2187 @CheckReturnValue2188 public <V, C extends Collection<V>> AbstractListAssert<?, List<? extends V>, V, ObjectAssert<V>> flatExtracting(Function<? super ELEMENT, C> extractor) {2189 return doFlatExtracting(extractor);2190 }2191 /**2192 * Extract the Iterable values from arrays elements under test by applying an Iterable extracting function (which2193 * might throw an exception) on them and concatenating the result lists into an array which becomes the new object2194 * under test.2195 * <p>2196 * It allows testing the results of extracting values that are represented by Iterables.2197 * <p>2198 * For example:2199 * <pre><code class='java'> CartoonCharacter bart = new CartoonCharacter("Bart Simpson");2200 * CartoonCharacter lisa = new CartoonCharacter("Lisa Simpson");2201 * CartoonCharacter maggie = new CartoonCharacter("Maggie Simpson");2202 * CartoonCharacter homer = new CartoonCharacter("Homer Simpson");2203 * homer.addChildren(bart, lisa, maggie);2204 *2205 * CartoonCharacter pebbles = new CartoonCharacter("Pebbles Flintstone");2206 * CartoonCharacter fred = new CartoonCharacter("Fred Flintstone");2207 * fred.getChildren().add(pebbles);2208 *2209 * CartoonCharacter[] parents = new CartoonCharacter[] { homer, fred };2210 * // check children2211 * assertThat(parents).flatExtracting(input -&gt; {2212 * if (input.getChildren().size() == 0) {2213 * throw new Exception("no children");2214 * }2215 * return input.getChildren();2216 * }).containsOnly(bart, lisa, maggie, pebbles);</code></pre>2217 *2218 * The order of extracted values is consisted with both the order of the collection itself, as well as the extracted2219 * collections.2220 *2221 * @param <V> the type of elements to extract.2222 * @param <C> the type of collection to flat/extract.2223 * @param <EXCEPTION> the exception type of {@link ThrowingExtractor}2224 * @param extractor the object transforming input object to an Iterable of desired ones2225 * @return a new assertion object whose object under test is the list of values extracted2226 * @since 3.7.02227 */2228 @CheckReturnValue2229 public <V, C extends Collection<V>, EXCEPTION extends Exception> AbstractListAssert<?, List<? extends V>, V, ObjectAssert<V>> flatExtracting(ThrowingExtractor<? super ELEMENT, C, EXCEPTION> extractor) {2230 return doFlatExtracting(extractor);2231 }2232 private <V, C extends Collection<V>> AbstractListAssert<?, List<? extends V>, V, ObjectAssert<V>> doFlatExtracting(Function<? super ELEMENT, C> extractor) {2233 List<V> result = FieldsOrPropertiesExtractor.extract(Arrays.asList(actual), extractor).stream()2234 .flatMap(Collection::stream).collect(toList());2235 return newListAssertInstance(result).withAssertionState(myself);2236 }2237 /**2238 * Extract from array's elements the Iterable/Array values corresponding to the given property/field name and2239 * concatenate them into a single array becoming the new object under test.2240 * <p>2241 * It allows testing the elements of extracting values that are represented by iterables or arrays.2242 * <p>2243 * For example:2244 * <pre><code class='java'> CartoonCharacter bart = new CartoonCharacter("Bart Simpson");2245 * CartoonCharacter lisa = new CartoonCharacter("Lisa Simpson");2246 * CartoonCharacter maggie = new CartoonCharacter("Maggie Simpson");2247 * CartoonCharacter homer = new CartoonCharacter("Homer Simpson");2248 * homer.addChildren(bart, lisa, maggie);2249 *2250 * CartoonCharacter pebbles = new CartoonCharacter("Pebbles Flintstone");2251 * CartoonCharacter fred = new CartoonCharacter("Fred Flintstone");2252 * fred.getChildren().add(pebbles);2253 *2254 * CartoonCharacter[] parents = new CartoonCharacter[] { homer, fred };2255 * // check children2256 * assertThat(parents).flatExtracting("children")2257 * .containsOnly(bart, lisa, maggie, pebbles);</code></pre>2258 *2259 * The order of extracted values is consisted with both the order of the collection itself, as well as the extracted2260 * collections.2261 *2262 * @param propertyName the object transforming input object to an Iterable of desired ones2263 * @return a new assertion object whose object under test is the list of values extracted2264 * @throws IllegalArgumentException if one of the extracted property value was not an array or an iterable.2265 */2266 @CheckReturnValue2267 public AbstractListAssert<?, List<? extends Object>, Object, ObjectAssert<Object>> flatExtracting(String propertyName) {2268 List<Object> extractedValues = newArrayList();2269 List<?> extractedGroups = FieldsOrPropertiesExtractor.extract(Arrays.asList(actual), byName(propertyName));2270 for (Object group : extractedGroups) {2271 // expecting group to be an iterable or an array2272 if (isArray(group)) {2273 int size = Array.getLength(group);2274 for (int i = 0; i < size; i++) {2275 extractedValues.add(Array.get(group, i));2276 }2277 } else if (group instanceof Iterable) {2278 Iterable<?> iterable = (Iterable<?>) group;2279 for (Object value : iterable) {2280 extractedValues.add(value);2281 }2282 } else {2283 CommonErrors.wrongElementTypeForFlatExtracting(group);2284 }2285 }2286 return newListAssertInstance(extractedValues).withAssertionState(myself);2287 }2288 /**2289 * Extract the result of given method invocation from the array's elements under test into a list, this list becoming2290 * the object under test.2291 * <p>2292 * It allows you to test a method results of the array's elements instead of testing the elements themselves, which can be2293 * much less work!2294 * <p>2295 * It is especially useful for classes that does not conform to the Java Bean's getter specification (i.e. public String2296 * toString() or public String status() instead of public String getStatus()).2297 * <p>2298 * Let's take an example to make things clearer :2299 * <pre><code class='java'> // Build a array of WesterosHouse, a WesterosHouse has a method: public String sayTheWords()2300 * WesterosHouse[] greatHousesOfWesteros = new WesterosHouse[] { new WesterosHouse(&quot;Stark&quot;, &quot;Winter is Coming&quot;),2301 * new WesterosHouse(&quot;Lannister&quot;, &quot;Hear Me Roar!&quot;), new WesterosHouse(&quot;Greyjoy&quot;, &quot;We Do Not Sow&quot;),2302 * new WesterosHouse(&quot;Baratheon&quot;, &quot;Our is the Fury&quot;), new WesterosHouse(&quot;Martell&quot;, &quot;Unbowed, Unbent, Unbroken&quot;),2303 * new WesterosHouse(&quot;Tyrell&quot;, &quot;Growing Strong&quot;) };2304 *2305 * // let's verify the words of the great houses of Westeros:2306 * assertThat(greatHousesOfWesteros).extractingResultOf(&quot;sayTheWords&quot;)2307 * .contains(&quot;Winter is Coming&quot;, &quot;We Do Not Sow&quot;, &quot;Hear Me Roar&quot;)2308 * .doesNotContain(&quot;Lannisters always pay their debts&quot;);</code></pre>2309 *2310 * <p>2311 * Following requirements have to be met to extract method results:2312 * <ul>2313 * <li>method has to be public,</li>2314 * <li>method cannot accept any arguments,</li>2315 * <li>method cannot return void.</li>2316 * </ul>2317 * <p>2318 * Note that the order of extracted values is consistent with the order of the array under test.2319 *2320 * @param method the name of the method which result is to be extracted from the array under test2321 * @return a new assertion object whose object under test is the list of extracted values.2322 * @throws IllegalArgumentException if no method exists with the given name, or method is not public, or method does2323 * return void, or method accepts arguments.2324 */2325 @CheckReturnValue2326 public AbstractListAssert<?, List<? extends Object>, Object, ObjectAssert<Object>> extractingResultOf(String method) {2327 Object[] values = FieldsOrPropertiesExtractor.extract(actual, resultOf(method));2328 String extractedDescription = extractedDescriptionOfMethod(method);2329 String description = mostRelevantDescription(info.description(), extractedDescription);2330 return newListAssertInstance(newArrayList(values)).withAssertionState(myself).as(description);2331 }2332 /**2333 * Extract the result of given method invocation from the array's elements under test into a list, this list becoming2334 * the object under test.2335 * <p>2336 * It allows you to test a method results of the array's elements instead of testing the elements themselves, which can be2337 * much less work!2338 * <p>2339 * It is especially useful for classes that do not conform to the Java Bean's getter specification (i.e. public String2340 * toString() or public String status() instead of public String getStatus()).2341 * <p>2342 * Let's take an example to make things clearer :2343 * <pre><code class='java'> // Build a array of WesterosHouse, a WesterosHouse has a method: public String sayTheWords()2344 * WesterosHouse[] greatHousesOfWesteros = new WesterosHouse[] { new WesterosHouse(&quot;Stark&quot;, &quot;Winter is Coming&quot;),2345 * new WesterosHouse(&quot;Lannister&quot;, &quot;Hear Me Roar!&quot;), new WesterosHouse(&quot;Greyjoy&quot;, &quot;We Do Not Sow&quot;),2346 * new WesterosHouse(&quot;Baratheon&quot;, &quot;Our is the Fury&quot;), new WesterosHouse(&quot;Martell&quot;, &quot;Unbowed, Unbent, Unbroken&quot;),2347 * new WesterosHouse(&quot;Tyrell&quot;, &quot;Growing Strong&quot;) };2348 *2349 * // let's verify the words of the great houses of Westeros:2350 * assertThat(greatHousesOfWesteros).extractingResultOf(&quot;sayTheWords&quot;, String.class)2351 * .contains(&quot;Winter is Coming&quot;, &quot;We Do Not Sow&quot;, &quot;Hear Me Roar&quot;)2352 * .doesNotContain(&quot;Lannisters always pay their debts&quot;);</code></pre>2353 *2354 * <p>2355 * Following requirements have to be met to extract method results:2356 * <ul>2357 * <li>method has to be public,</li>2358 * <li>method can not accept any arguments,</li>2359 * <li>method can not return void.</li>2360 * </ul>2361 * <p>2362 * Note that the order of extracted values is consistent with the order of the array under test.2363 *2364 * @param <P> the type of elements extracted.2365 * @param method the name of the method which result is to be extracted from the array under test2366 * @param extractingType type to return2367 * @return a new assertion object whose object under test is the list of extracted values.2368 * @throws IllegalArgumentException if no method exists with the given name, or method is not public, or method does2369 * return void, or method accepts arguments.2370 */2371 @CheckReturnValue2372 public <P> AbstractListAssert<?, List<? extends P>, P, ObjectAssert<P>> extractingResultOf(String method,2373 Class<P> extractingType) {2374 @SuppressWarnings("unchecked")2375 P[] values = (P[]) FieldsOrPropertiesExtractor.extract(actual, resultOf(method));2376 String extractedDescription = extractedDescriptionOfMethod(method);2377 String description = mostRelevantDescription(info.description(), extractedDescription);2378 return newListAssertInstance(newArrayList(values)).withAssertionState(myself).as(description);2379 }2380 /**2381 * Enable hexadecimal object representation of Iterable elements instead of standard java representation in error2382 * messages.2383 * <p>2384 * It can be useful to better understand what the error was with a more meaningful error message.2385 * <p>2386 * Example2387 * <pre><code class='java'> assertThat(new Byte[] { 0x10, 0x20 }).inHexadecimal().contains(new Byte[] { 0x30 });</code></pre>2388 *2389 * With standard error message:2390 * <pre><code class='java'> Expecting:2391 * &lt;[16, 32]&gt;2392 * to contain:2393 * &lt;[48]&gt;2394 * but could not find:2395 * &lt;[48]&gt;</code></pre>2396 *2397 * With Hexadecimal error message:2398 * <pre><code class='java'> Expecting:2399 * &lt;[0x10, 0x20]&gt;2400 * to contain:2401 * &lt;[0x30]&gt;2402 * but could not find:2403 * &lt;[0x30]&gt;</code></pre>2404 *2405 * @return {@code this} assertion object.2406 */2407 @Override2408 @CheckReturnValue2409 public SELF inHexadecimal() {2410 return super.inHexadecimal();2411 }2412 @Override2413 @CheckReturnValue2414 public SELF inBinary() {2415 return super.inBinary();2416 }2417 /**2418 * Filter the array under test into a list composed of the elements elements having a property or field equal to2419 * {@code expectedValue}, the property/field is specified by {@code propertyOrFieldName} parameter.2420 * <p>2421 * The filter first tries to get the value from a property (named {@code propertyOrFieldName}), if no such property2422 * exists it tries to read the value from a field. Reading private fields is supported by default, this can be2423 * globally disabled by calling {@link Assertions#setAllowExtractingPrivateFields(boolean)2424 * Assertions.setAllowExtractingPrivateFields(false)}.2425 * <p>2426 * When reading <b>nested</b> property/field, if an intermediate value is null the whole nested property/field is2427 * considered to be null, thus reading "address.street.name" value will return null if "street" value is null.2428 * <p>2429 *2430 * As an example, let's check all employees 800 years old (yes, special employees):2431 * <pre><code class='java'> Employee yoda = new Employee(1L, new Name("Yoda"), 800);2432 * Employee obiwan = new Employee(2L, new Name("Obiwan"), 800);2433 * Employee luke = new Employee(3L, new Name("Luke", "Skywalker"), 26);2434 * Employee noname = new Employee(4L, null, 50);2435 *2436 * Employee[] employees = new Employee[] { yoda, luke, obiwan, noname };2437 *2438 * assertThat(employees).filteredOn("age", 800)2439 * .containsOnly(yoda, obiwan);</code></pre>2440 *2441 * Nested properties/fields are supported:2442 * <pre><code class='java'> // Name is bean class with 'first' and 'last' String properties2443 *2444 * // name is null for noname =&gt; it does not match the filter on "name.first"2445 * assertThat(employees).filteredOn("name.first", "Luke")2446 * .containsOnly(luke);2447 *2448 * assertThat(employees).filteredOn("name.last", "Vader")2449 * .isEmpty();</code></pre>2450 * <p>2451 * If you want to filter on null value, use {@link #filteredOnNull(String)} as Java will resolve the call to2452 * {@link #filteredOn(String, FilterOperator)} instead of this method.2453 * <p>2454 * An {@link IntrospectionError} is thrown if the given propertyOrFieldName can't be found in one of the array2455 * elements.2456 * <p>2457 * You can chain filters:2458 * <pre><code class='java'> // fellowshipOfTheRing is an array of TolkienCharacter having race and name fields2459 * // 'not' filter is statically imported from Assertions.not2460 *2461 * assertThat(fellowshipOfTheRing).filteredOn("race.name", "Man")2462 * .filteredOn("name", not("Boromir"))2463 * .containsOnly(aragorn);</code></pre>2464 * <p>2465 * If you need more complex filter, use {@link #filteredOn(Condition)} or {@link #filteredOn(Predicate)} and2466 * provide a {@link Condition} or {@link Predicate} to specify the filter to apply.2467 *2468 * @param propertyOrFieldName the name of the property or field to read2469 * @param expectedValue the value to compare element's property or field with2470 * @return a new assertion object with the filtered list under test2471 * @throws IllegalArgumentException if the given propertyOrFieldName is {@code null} or empty.2472 * @throws IntrospectionError if the given propertyOrFieldName can't be found in one of the array elements.2473 */2474 @CheckReturnValue2475 public SELF filteredOn(String propertyOrFieldName, Object expectedValue) {2476 List<ELEMENT> filteredList = filter(actual).with(propertyOrFieldName, expectedValue).get();2477 return newObjectArrayAssert(filteredList);2478 }2479 /**2480 * Filter the array under test into a list composed of the elements whose property or field specified2481 * by {@code propertyOrFieldName} are null.2482 * <p>2483 * The filter first tries to get the value from a property (named {@code propertyOrFieldName}), if no such property2484 * exists it tries to read the value from a field. Reading private fields is supported by default, this can be2485 * globally disabled by calling {@link Assertions#setAllowExtractingPrivateFields(boolean)2486 * Assertions.setAllowExtractingPrivateFields(false)}.2487 * <p>2488 * When reading <b>nested</b> property/field, if an intermediate value is null the whole nested property/field is2489 * considered to be null, thus reading "address.street.name" value will return null if "street" value is null.2490 * <p>2491 * As an example, let's check all employees 800 years old (yes, special employees):2492 * <pre><code class='java'> Employee yoda = new Employee(1L, new Name("Yoda"), 800);2493 * Employee obiwan = new Employee(2L, new Name("Obiwan"), 800);2494 * Employee luke = new Employee(3L, new Name("Luke", "Skywalker"), 26);2495 * Employee noname = new Employee(4L, null, 50);2496 *2497 * Employee[] employees = new Employee[] { yoda, luke, obiwan, noname };2498 *2499 * assertThat(employees).filteredOnNull("name")2500 * .containsOnly(noname);</code></pre>2501 *2502 * Nested properties/fields are supported:2503 * <pre><code class='java'> // Name is bean class with 'first' and 'last' String properties2504 *2505 * assertThat(employees).filteredOnNull("name.last")2506 * .containsOnly(yoda, obiwan, noname);</code></pre>2507 *2508 * An {@link IntrospectionError} is thrown if the given propertyOrFieldName can't be found in one of the array2509 * elements.2510 *2511 * @param propertyOrFieldName the name of the property or field to read2512 * @return a new assertion object with the filtered list under test2513 * @throws IntrospectionError if the given propertyOrFieldName can't be found in one of the array elements.2514 */2515 @CheckReturnValue2516 public SELF filteredOnNull(String propertyOrFieldName) {2517 // can't call filteredOn(String propertyOrFieldName, null) as it does not work with soft assertions proxying2518 // mechanism, it would lead to double proxying which is not handle properly (improvements needed in our proxy mechanism)2519 List<ELEMENT> filteredList = filter(actual).with(propertyOrFieldName, null).get();2520 return newObjectArrayAssert(filteredList);2521 }2522 /**2523 * Filter the array under test into a list composed of elements having a property or field matching the filter expressed with2524 * the {@link FilterOperator}, the property/field is specified by {@code propertyOrFieldName} parameter.2525 * <p>2526 * The existing filters are :2527 * <ul>2528 * <li> {@link Assertions#not(Object) not(Object)}</li>2529 * <li> {@link Assertions#in(Object...) in(Object...)}</li>2530 * <li> {@link Assertions#notIn(Object...) notIn(Object...)}</li>2531 * </ul>2532 * <p>2533 * Whatever filter is applied, it first tries to get the value from a property (named {@code propertyOrFieldName}), if2534 * no such property exists it tries to read the value from a field. Reading private fields is supported by default,2535 * this can be globally disabled by calling {@link Assertions#setAllowExtractingPrivateFields(boolean)2536 * Assertions.setAllowExtractingPrivateFields(false)}.2537 * <p>2538 * When reading <b>nested</b> property/field, if an intermediate value is null the whole nested property/field is2539 * considered to be null, thus reading "address.street.name" value will return null if "street" value is null.2540 * <p>2541 * As an example, let's check stuff on some special employees :2542 * <pre><code class='java'> Employee yoda = new Employee(1L, new Name("Yoda"), 800);2543 * Employee obiwan = new Employee(2L, new Name("Obiwan"), 800);2544 * Employee luke = new Employee(3L, new Name("Luke", "Skywalker"), 26);2545 *2546 * Employee[] employees = new Employee[] { yoda, luke, obiwan, noname };2547 *2548 * // 'not' filter is statically imported from Assertions.not2549 * assertThat(employees).filteredOn("age", not(800))2550 * .containsOnly(luke);2551 *2552 * // 'in' filter is statically imported from Assertions.in2553 * // Name is bean class with 'first' and 'last' String properties2554 * assertThat(employees).filteredOn("name.first", in("Yoda", "Luke"))2555 * .containsOnly(yoda, luke);2556 *2557 * // 'notIn' filter is statically imported from Assertions.notIn2558 * assertThat(employees).filteredOn("name.first", notIn("Yoda", "Luke"))2559 * .containsOnly(obiwan);</code></pre>2560 *2561 * An {@link IntrospectionError} is thrown if the given propertyOrFieldName can't be found in one of the array2562 * elements.2563 * <p>2564 * Note that combining filter operators is not supported, thus the following code is not correct:2565 * <pre><code class='java'> // Combining filter operators like not(in(800)) is NOT supported2566 * // -&gt; throws UnsupportedOperationException2567 * assertThat(employees).filteredOn("age", not(in(800)))2568 * .contains(luke);</code></pre>2569 * <p>2570 * You can chain filters:2571 * <pre><code class='java'> // fellowshipOfTheRing is an array of TolkienCharacter having race and name fields2572 * // 'not' filter is statically imported from Assertions.not2573 *2574 * assertThat(fellowshipOfTheRing).filteredOn("race.name", "Man")2575 * .filteredOn("name", not("Boromir"))2576 * .containsOnly(aragorn);</code></pre>2577 * <p>2578 * If you need more complex filter, use {@link #filteredOn(Condition)} or {@link #filteredOn(Predicate)} and2579 * provide a {@link Condition} or {@link Predicate} to specify the filter to apply.2580 *2581 * @param propertyOrFieldName the name of the property or field to read2582 * @param filterOperator the filter operator to apply2583 * @return a new assertion object with the filtered list under test2584 * @throws IllegalArgumentException if the given propertyOrFieldName is {@code null} or empty.2585 */2586 @CheckReturnValue2587 public SELF filteredOn(String propertyOrFieldName, FilterOperator<?> filterOperator) {2588 checkNotNull(filterOperator);2589 Filters<ELEMENT> filter = filter(actual).with(propertyOrFieldName);2590 filterOperator.applyOn(filter);2591 return newObjectArrayAssert(filter.get());2592 }2593 /**2594 * Filter the array under test into a list composed of the elements matching the given {@link Condition},2595 * allowing to perform assertions on the filtered list.2596 * <p>2597 * Let's check old employees whose age &gt; 100:2598 * <pre><code class='java'> Employee yoda = new Employee(1L, new Name("Yoda"), 800);2599 * Employee obiwan = new Employee(2L, new Name("Obiwan"), 800);2600 * Employee luke = new Employee(3L, new Name("Luke", "Skywalker"), 26);2601 * Employee noname = new Employee(4L, null, 50);2602 *2603 * Employee[] employees = new Employee[] { yoda, luke, obiwan, noname };2604 *2605 * // old employee condition, "old employees" describes the condition in error message2606 * // you just have to implement 'matches' method2607 * Condition&lt;Employee&gt; oldEmployees = new Condition&lt;Employee&gt;("old employees") {2608 * {@literal @}Override2609 * public boolean matches(Employee employee) {2610 * return employee.getAge() &gt; 100;2611 * }2612 * };2613 * }2614 * assertThat(employees).filteredOn(oldEmployees)2615 * .containsOnly(yoda, obiwan);</code></pre>2616 *2617 * You can combine {@link Condition} with condition operator like {@link Not}:2618 * <pre><code class='java'> // 'not' filter is statically imported from Assertions.not2619 * assertThat(employees).filteredOn(not(oldEmployees))2620 * .contains(luke, noname);</code></pre>2621 *2622 * @param condition the filter condition / predicate2623 * @return a new assertion object with the filtered list under test2624 * @throws IllegalArgumentException if the given condition is {@code null}.2625 */2626 @CheckReturnValue2627 public SELF filteredOn(Condition<? super ELEMENT> condition) {2628 List<ELEMENT> filteredList = filter(actual).being(condition).get();2629 return newObjectArrayAssert(filteredList);2630 }2631 /**2632 * Filter the array under test into a list composed of the elements matching the given {@link Predicate},2633 * allowing to perform assertions on the filtered list.2634 * <p>2635 * Example : check old employees whose age &gt; 100:2636 *2637 * <pre><code class='java'> Employee yoda = new Employee(1L, new Name("Yoda"), 800);2638 * Employee obiwan = new Employee(2L, new Name("Obiwan"), 800);2639 * Employee luke = new Employee(3L, new Name("Luke", "Skywalker"), 26);2640 *2641 * Employee[] employees = new Employee[] { yoda, luke, obiwan };2642 *2643 * assertThat(employees).filteredOn(employee -&gt; employee.getAge() &gt; 100)2644 * .containsOnly(yoda, obiwan);</code></pre>2645 *2646 * @param predicate the filter predicate2647 * @return a new assertion object with the filtered list under test2648 * @throws IllegalArgumentException if the given predicate is {@code null}.2649 */2650 public SELF filteredOn(Predicate<? super ELEMENT> predicate) {2651 return internalFilteredOn(predicate);2652 }2653 /**2654 * Filter the array under test into a list composed of the elements for which the result of the {@code function} is equal to {@code expectedValue}.2655 * <p>2656 * It allows to filter elements in more safe way than by using {@link #filteredOn(String, Object)} as it doesn't utilize introspection.2657 * <p>2658 * As an example, let's check all employees 800 years old (yes, special employees):2659 * <pre><code class='java'> Employee yoda = new Employee(1L, new Name("Yoda"), 800);2660 * Employee obiwan = new Employee(2L, new Name("Obiwan"), 800);2661 * Employee luke = new Employee(3L, new Name("Luke", "Skywalker"), 26);2662 * Employee noname = new Employee(4L, null, 50);2663 *2664 * Employee[] employees = new Employee[] { yoda, luke, obiwan, noname };2665 *2666 * assertThat(employees).filteredOn(Employee::getAge, 800)2667 * .containsOnly(yoda, obiwan);2668 *2669 * assertThat(employees).filteredOn(e -&gt; e.getName(), null)2670 * .containsOnly(noname);</code></pre>2671 *2672 * If you need more complex filter, use {@link #filteredOn(Predicate)} or {@link #filteredOn(Condition)}.2673 *2674 * @param <T> result type of the filter function2675 * @param function the filter function2676 * @param expectedValue the expected value of the filter function2677 * @return a new assertion object with the filtered list under test2678 * @throws IllegalArgumentException if the given function is {@code null}.2679 * @since 3.17.02680 */2681 @CheckReturnValue2682 public <T> SELF filteredOn(Function<? super ELEMENT, T> function, T expectedValue) {2683 checkArgument(function != null, "The filter function should not be null");2684 // call internalFilteredOn to avoid double proxying in soft assertions2685 return internalFilteredOn(element -> java.util.Objects.equals(function.apply(element), expectedValue));2686 }2687 /**2688 * Filter the array under test keeping only elements matching the given assertions specified with a {@link Consumer}.2689 * <p>2690 * Example : check old employees whose age &gt; 100:2691 *2692 * <pre><code class='java'> Employee yoda = new Employee(1L, new Name("Yoda"), 800);2693 * Employee obiwan = new Employee(2L, new Name("Obiwan"), 800);2694 * Employee luke = new Employee(3L, new Name("Luke", "Skywalker"), 26);2695 *2696 * Employee[] employees = new Employee[] { yoda, luke, obiwan };2697 *2698 * assertThat(employees).filteredOnAssertions(employee -&gt; assertThat(employee.getAge()).isGreaterThan(100))2699 * .containsOnly(yoda, obiwan);</code></pre>2700 *2701 * @param elementAssertions containing AssertJ assertions to filter on2702 * @return a new assertion object with the filtered iterable under test2703 * @throws IllegalArgumentException if the given predicate is {@code null}.2704 * @since 3.11.02705 */2706 public SELF filteredOnAssertions(Consumer<? super ELEMENT> elementAssertions) {2707 checkArgument(elementAssertions != null, "The element assertions should not be null");2708 List<ELEMENT> filteredIterable = stream(actual).filter(byPassingAssertions(elementAssertions)).collect(toList());2709 return newObjectArrayAssert(filteredIterable).withAssertionState(myself);2710 }2711 /**2712 * Verifies that all elements match the given {@link Predicate}.2713 * <p>2714 * Example :2715 * <pre><code class='java'> String[] abc = {"a", "b", "c"};2716 * String[] abcc = {"a", "b", "cc"};2717 *2718 * // assertion will pass2719 * assertThat(abc).allMatch(s -&gt; s.length() == 1);2720 *2721 * // assertion will fail2722 * assertThat(abcc).allMatch(s -&gt; s.length() == 1);</code></pre>2723 *2724 * Note that you can achieve the same result with {@link #are(Condition) are(Condition)} or {@link #have(Condition) have(Condition)}.2725 *2726 * @param predicate the given {@link Predicate}.2727 * @return {@code this} object.2728 * @throws NullPointerException if the given predicate is {@code null}.2729 * @throws AssertionError if an element cannot be cast to ELEMENT.2730 * @throws AssertionError if one or more elements don't satisfy the given predicate.2731 */2732 @Override2733 public SELF allMatch(Predicate<? super ELEMENT> predicate) {2734 iterables.assertAllMatch(info, newArrayList(actual), predicate, PredicateDescription.GIVEN);2735 return myself;2736 }2737 /**2738 * {@inheritDoc}2739 */2740 @Override2741 public SELF allMatch(Predicate<? super ELEMENT> predicate, String predicateDescription) {2742 iterables.assertAllMatch(info, newArrayList(actual), predicate, new PredicateDescription(predicateDescription));2743 return myself;2744 }2745 /**2746 * {@inheritDoc}2747 */2748 @Override2749 public SELF allSatisfy(Consumer<? super ELEMENT> requirements) {2750 iterables.assertAllSatisfy(info, newArrayList(actual), requirements);2751 return myself;2752 }2753 /**2754 * Verifies whether any elements match the provided {@link Predicate}.2755 * <p>2756 * Example :2757 * <pre><code class='java'> String[] abcc = { "a", "b", "cc" };2758 *2759 * // assertion will pass2760 * assertThat(abc).anyMatch(s -&gt; s.length() == 2);2761 *2762 * // assertion will fail2763 * assertThat(abcc).anyMatch(s -&gt; s.length() &gt; 2);</code></pre>2764 *2765 * Note that you can achieve the same result with {@link #areAtLeastOne(Condition) areAtLeastOne(Condition)}2766 * or {@link #haveAtLeastOne(Condition) haveAtLeastOne(Condition)}.2767 *2768 * @param predicate the given {@link Predicate}.2769 * @return {@code this} object.2770 * @throws NullPointerException if the given predicate is {@code null}.2771 * @throws AssertionError if no elements satisfy the given predicate.2772 * @since 3.9.02773 */2774 @Override2775 public SELF anyMatch(Predicate<? super ELEMENT> predicate) {2776 iterables.assertAnyMatch(info, newArrayList(actual), predicate, PredicateDescription.GIVEN);2777 return myself;2778 }2779 /**2780 * Verifies that the zipped pairs of actual and other elements, i.e: (actual 1st element, other 1st element), (actual 2nd element, other 2nd element), ...2781 * all satisfy the given {@code zipRequirements}.2782 * <p>2783 * This assertion assumes that actual and other have the same size but they can contain different type of elements2784 * making it handy to compare objects converted to another type, for example Domain and View/DTO objects.2785 * <p>2786 * Example:2787 * <pre><code class='java'> Adress[] addressModels = findGoodRestaurants();2788 * AdressView[] addressViews = convertToView(addressModels);2789 *2790 * // compare addressViews and addressModels respective paired elements.2791 * assertThat(addressViews).zipSatisfy(addressModels, (AdressView view, Adress model) -&gt; {2792 * assertThat(view.getZipcode() + ' ' + view.getCity()).isEqualTo(model.getCityLine());2793 * assertThat(view.getStreet()).isEqualTo(model.getStreet().toUpperCase());2794 * });</code></pre>2795 *2796 * @param <OTHER_ELEMENT> the type of the other array elements.2797 * @param other the array to zip actual with.2798 * @param zipRequirements the given requirements that each pair must satisfy.2799 * @return {@code this} assertion object.2800 * @throws NullPointerException if the given zipRequirements {@link BiConsumer} is {@code null}.2801 * @throws NullPointerException if the other array to zip actual with is {@code null}.2802 * @throws AssertionError if the array under test is {@code null}.2803 * @throws AssertionError if actual and other don't have the same size.2804 * @throws AssertionError if one or more pairs don't satisfy the given requirements.2805 * @since 3.9.02806 */2807 public <OTHER_ELEMENT> SELF zipSatisfy(OTHER_ELEMENT[] other,2808 BiConsumer<? super ELEMENT, OTHER_ELEMENT> zipRequirements) {2809 iterables.assertZipSatisfy(info, newArrayList(actual), newArrayList(other), zipRequirements);2810 return myself;2811 }2812 /**2813 * {@inheritDoc}2814 */2815 @Override2816 public SELF anySatisfy(Consumer<? super ELEMENT> requirements) {2817 iterables.assertAnySatisfy(info, newArrayList(actual), requirements);2818 return myself;2819 }2820 /**2821 * {@inheritDoc}2822 */2823 @Override2824 public SELF noneSatisfy(Consumer<? super ELEMENT> restrictions) {2825 iterables.assertNoneSatisfy(info, newArrayList(actual), restrictions);2826 return myself;2827 }2828 /**2829 * Verifies that the actual array contains at least one of the given values.2830 * <p>2831 * Example :2832 * <pre><code class='java'> String[] abc = {"a", "b", "c"};2833 *2834 * // assertions will pass2835 * assertThat(abc).containsAnyOf("b")2836 * .containsAnyOf("b", "c")2837 * .containsAnyOf("a", "b", "c")2838 * .containsAnyOf("a", "b", "c", "d")2839 * .containsAnyOf("e", "f", "g", "b");2840 *2841 * // assertions will fail2842 * assertThat(abc).containsAnyOf("d");2843 * assertThat(abc).containsAnyOf("d", "e", "f", "g");</code></pre>2844 *2845 * @param values the values whose at least one which is expected to be in the array under test.2846 * @return {@code this} assertion object.2847 * @throws NullPointerException if the array of values is {@code null}.2848 * @throws IllegalArgumentException if the array of values is empty and the array under test is not empty.2849 * @throws AssertionError if the array under test is {@code null}.2850 * @throws AssertionError if the array under test does not contain any of the given {@code values}.2851 * @since 2.9.0 / 3.9.02852 */2853 @Override2854 public SELF containsAnyOf(@SuppressWarnings("unchecked") ELEMENT... values) {2855 arrays.assertContainsAnyOf(info, actual, values);2856 return myself;2857 }2858 /**2859 * Verifies that the actual array contains at least one of the given {@link Iterable} elements.2860 * <p>2861 * Example :2862 * <pre><code class='java'> String[] abc = {"a", "b", "c"};2863 *2864 * // assertions will pass2865 * assertThat(abc).containsAnyElementsOf(Arrays.asList("b"))2866 * .containsAnyElementsOf(Arrays.asList("b", "c"))2867 * .containsAnyElementsOf(Arrays.asList("a", "b", "c"))2868 * .containsAnyElementsOf(Arrays.asList("a", "b", "c", "d"))2869 * .containsAnyElementsOf(Arrays.asList("e", "f", "g", "b"));2870 *2871 * // assertions will fail2872 * assertThat(abc).containsAnyElementsOf(Arrays.asList("d"));2873 * assertThat(abc).containsAnyElementsOf(Arrays.asList("d", "e", "f", "g"));</code></pre>2874 *2875 * @param iterable the iterable whose at least one element is expected to be in the array under test.2876 * @return {@code this} assertion object.2877 * @throws NullPointerException if the iterable of expected values is {@code null}.2878 * @throws IllegalArgumentException if the iterable of expected values is empty and the array under test is not empty.2879 * @throws AssertionError if the array under test is {@code null}.2880 * @throws AssertionError if the array under test does not contain any of elements from the given {@code Iterable}.2881 * @since 2.9.0 / 3.9.02882 */2883 @Override2884 public SELF containsAnyElementsOf(Iterable<? extends ELEMENT> iterable) {2885 return containsAnyOf(toArray(iterable));2886 }2887 /**2888 * Verifies that no elements match the given {@link Predicate}.2889 * <p>2890 * Example :2891 * <pre><code class='java'> String[] abcc = { "a", "b", "cc" };2892 *2893 * // assertion will pass2894 * assertThat(abcc).noneMatch(s -&gt; s.isEmpty());2895 *2896 * // assertion will fail2897 * assertThat(abcc).noneMatch(s -&gt; s.length() == 2);</code></pre>2898 *2899 * Note that you can achieve the same result with {@link #areNot(Condition) areNot(Condition)}2900 * or {@link #doNotHave(Condition) doNotHave(Condition)}.2901 *2902 * @param predicate the given {@link Predicate}.2903 * @return {@code this} object.2904 * @throws NullPointerException if the given predicate is {@code null}.2905 * @throws AssertionError if an element cannot be cast to ELEMENT.2906 * @throws AssertionError if any element satisfy the given predicate.2907 * @since 3.9.02908 */2909 @Override2910 public SELF noneMatch(Predicate<? super ELEMENT> predicate) {2911 iterables.assertNoneMatch(info, newArrayList(actual), predicate, PredicateDescription.GIVEN);2912 return myself;2913 }2914 /**2915 * Create a friendly soft or "hard" assertion.2916 * <p>2917 * Implementations need to redefine it so that some methods, such as {@link #extracting(Function)}, are able2918 * to build the appropriate list assert (eg: {@link ListAssert} versus {@link ProxyableListAssert}).2919 * <p>2920 * The default implementation will assume that this concrete implementation is NOT a soft assertion.2921 *2922 * @param <E> the type of elements.2923 * @param newActual new value2924 * @return a new {@link AbstractListAssert}.2925 */2926 @Override2927 protected <E> AbstractListAssert<?, List<? extends E>, E, ObjectAssert<E>> newListAssertInstance(List<? extends E> newActual) {2928 return new ListAssert<>(newActual);2929 }2930 /**2931 * Enable using a recursive field by field comparison strategy when calling the chained {@link RecursiveComparisonAssert},2932 * <p>2933 * Example:2934 * <pre><code class='java'> public class Person {2935 * String name;2936 * boolean hasPhd;2937 * }2938 *2939 * public class Doctor {2940 * String name;2941 * boolean hasPhd;2942 * }2943 *2944 * Doctor drSheldon = new Doctor("Sheldon Cooper", true);2945 * Doctor drLeonard = new Doctor("Leonard Hofstadter", true);2946 * Doctor drRaj = new Doctor("Raj Koothrappali", true);2947 *2948 * Person sheldon = new Person("Sheldon Cooper", true);2949 * Person leonard = new Person("Leonard Hofstadter", true);2950 * Person raj = new Person("Raj Koothrappali", true);2951 * Person howard = new Person("Howard Wolowitz", false);2952 *2953 * Doctor[] doctors = { drSheldon, drLeonard, drRaj };2954 * Person[] people = { sheldon, leonard, raj };2955 *2956 * // assertion succeeds as both lists contains equivalent items in order.2957 * assertThat(doctors).usingRecursiveComparison()2958 * .isEqualTo(people);2959 *2960 * // assertion fails because leonard names are different.2961 * leonard.setName("Leonard Ofstater");2962 * assertThat(doctors).usingRecursiveComparison()2963 * .isEqualTo(people);2964 *2965 * // assertion fails because howard is missing and leonard is not expected.2966 * Person[] otherPeople = { howard, sheldon, raj };2967 * assertThat(doctors).usingRecursiveComparison()2968 * .isEqualTo(otherPeople);</code></pre>2969 *2970 * 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>.2971 * <p>2972 * The default recursive comparison behavior is {@link RecursiveComparisonConfiguration configured} as follows:2973 * <ul>2974 * <li> different types of iterable can be compared by default, this allows to compare for example an {@code Person[]} and a {@code PersonDto[]}.<br>2975 * This behavior can be turned off by calling {@link RecursiveComparisonAssert#withStrictTypeChecking() withStrictTypeChecking}.</li>2976 * <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>2977 * <li>the following types are compared with these comparators:2978 * <ul>2979 * <li>{@code java.lang.Double}: {@code DoubleComparator} with precision of 1.0E-15</li>2980 * <li>{@code java.lang.Float}: {@code FloatComparator }with precision of 1.0E-6</li>2981 * <li>any comparators previously registered with {@link AbstractIterableAssert#usingComparatorForType(Comparator, Class)} </li>2982 * </ul>2983 * </li>2984 * </ul>2985 *2986 * @return a new {@link RecursiveComparisonAssert} instance2987 * @see RecursiveComparisonConfiguration RecursiveComparisonConfiguration2988 */2989 @Override2990 @Beta2991 public RecursiveComparisonAssert<?> usingRecursiveComparison() {2992 // overridden for javadoc and to make this method public2993 return super.usingRecursiveComparison();2994 }2995 /**2996 * Same as {@link #usingRecursiveComparison()} but allows to specify your own {@link RecursiveComparisonConfiguration}.2997 * @param recursiveComparisonConfiguration the {@link RecursiveComparisonConfiguration} used in the chained {@link RecursiveComparisonAssert#isEqualTo(Object) isEqualTo} assertion.2998 *2999 * @return a new {@link RecursiveComparisonAssert} instance built with the given {@link RecursiveComparisonConfiguration}.3000 */3001 @Override3002 public RecursiveComparisonAssert<?> usingRecursiveComparison(RecursiveComparisonConfiguration recursiveComparisonConfiguration) {3003 return super.usingRecursiveComparison(recursiveComparisonConfiguration).withTypeComparators(comparatorsByType);3004 }3005 // lazy init TypeComparators3006 protected TypeComparators getComparatorsByType() {3007 if (comparatorsByType == null) comparatorsByType = defaultTypeComparators();3008 return comparatorsByType;3009 }3010 // lazy init TypeComparators3011 protected TypeComparators getComparatorsForElementPropertyOrFieldTypes() {3012 if (comparatorsForElementPropertyOrFieldTypes == null) comparatorsForElementPropertyOrFieldTypes = defaultTypeComparators();3013 return comparatorsForElementPropertyOrFieldTypes;3014 }3015 @SuppressWarnings({ "rawtypes", "unchecked" })3016 @Override3017 SELF withAssertionState(AbstractAssert assertInstance) {3018 if (assertInstance instanceof AbstractObjectArrayAssert) {3019 AbstractObjectArrayAssert objectArrayAssert = (AbstractObjectArrayAssert) assertInstance;3020 return (SELF) super.withAssertionState(assertInstance).withIterables(objectArrayAssert.iterables)3021 .withObjectArrays(objectArrayAssert.arrays)3022 .withTypeComparators(objectArrayAssert.comparatorsByType)3023 .withComparatorsForElementPropertyOrFieldNames(objectArrayAssert.comparatorsForElementPropertyOrFieldNames)3024 .withComparatorsForElementPropertyOrFieldTypes(objectArrayAssert.comparatorsForElementPropertyOrFieldTypes);3025 }...

Full Screen

Full Screen

getComparatorsForElementPropertyOrFieldTypes

Using AI Code Generation

copy

Full Screen

1package org.assertj.core.api.objectarray;2import static org.assertj.core.api.Assertions.assertThat;3import java.util.Comparator;4import org.assertj.core.api.AbstractObjectArrayAssert;5import org.assertj.core.test.Jedi;6import org.junit.Test;7public class ObjectArrayAssert_getComparatorsForElementPropertyOrFieldTypes_Test {8 public void should_return_comparator_for_element_property_or_field_type() {9 Jedi actual = new Jedi("Yoda", "Green");10 Jedi other = new Jedi("Luke", "Green");11 Jedi[] array = { actual, other };12 Comparator<? super Jedi> comparator = AbstractObjectArrayAssert.getComparatorsForElementPropertyOrFieldTypes(array, "name");13 assertThat(comparator.compare(actual, other)).isLessThan(0);14 }15}16org.assertj.core.api.objectarray.ObjectArrayAssert_getComparatorsForElementPropertyOrFieldTypes_Test > should_return_comparator_for_element_property_or_field_type() PASSED

Full Screen

Full Screen

getComparatorsForElementPropertyOrFieldTypes

Using AI Code Generation

copy

Full Screen

1import org.assertj.core.api.AbstractObjectArrayAssert;2import org.assertj.core.api.Assertions;3public class getComparatorsForElementPropertyOrFieldTypes {4 public static void main(String[] args) {5 AbstractObjectArrayAssert<?, ?> objectArrayAssert = Assertions.assertThat(new String[] { "One", "Two", "Three" });6 objectArrayAssert.getComparatorsForElementPropertyOrFieldTypes();7 }8}9 at org.assertj.core.api.AbstractObjectArrayAssert.getComparatorsForElementPropertyOrFieldTypes(AbstractObjectArrayAssert.java:257)10 at getComparatorsForElementPropertyOrFieldTypes.main(1.java:8)

Full Screen

Full Screen

getComparatorsForElementPropertyOrFieldTypes

Using AI Code Generation

copy

Full Screen

1import org.assertj.core.api.Assertions;2import org.assertj.core.api.ObjectArrayAssert;3import org.assertj.core.api.ObjectArrayAssertBaseTest;4import org.assertj.core.util.introspection.IntrospectionError;5import java.util.Comparator;6public class Demo {7 public static void main(String[] args) {8 ObjectArrayAssert<Object> objectObjectArrayAssert = Assertions.assertThat(new Object[0]);9 Comparator<?>[] comparatorsForElementPropertyOrFieldTypes = objectObjectArrayAssert.getComparatorsForElementPropertyOrFieldTypes();10 System.out.println(comparatorsForElementPropertyOrFieldTypes);11 }12}

Full Screen

Full Screen

getComparatorsForElementPropertyOrFieldTypes

Using AI Code Generation

copy

Full Screen

1package org.assertj.core.api;2public class AssertJCore_getComparatorsForElementPropertyOrFieldTypes1 {3 public static void getComparatorsForElementPropertyOrFieldTypes1() {4 AbstractObjectArrayAssert<?, ?> assertions = null;5 Map<String, Comparator<?>> map = assertions.getComparatorsForElementPropertyOrFieldTypes();6 }7}8package org.assertj.core.api;9public class AssertJCore_getComparatorsForElementPropertyOrFieldTypes2 {10 public static void getComparatorsForElementPropertyOrFieldTypes2() {11 AbstractObjectArrayAssert<?, ?> assertions = null;12 Map<String, Comparator<?>> map = assertions.getComparatorsForElementPropertyOrFieldTypes();13 }14}15package org.assertj.core.api;16public class AssertJCore_getComparatorsForElementPropertyOrFieldTypes3 {17 public static void getComparatorsForElementPropertyOrFieldTypes3() {18 AbstractObjectArrayAssert<?, ?> assertions = null;19 Map<String, Comparator<?>> map = assertions.getComparatorsForElementPropertyOrFieldTypes();20 }21}22package org.assertj.core.api;23public class AssertJCore_getComparatorsForElementPropertyOrFieldTypes4 {24 public static void getComparatorsForElementPropertyOrFieldTypes4() {25 AbstractObjectArrayAssert<?, ?> assertions = null;26 Map<String, Comparator<?>> map = assertions.getComparatorsForElementPropertyOrFieldTypes();27 }28}29package org.assertj.core.api;30public class AssertJCore_getComparatorsForElementPropertyOrFieldTypes5 {31 public static void getComparatorsForElementPropertyOrFieldTypes5() {32 AbstractObjectArrayAssert<?, ?> assertions = null;33 Map<String, Comparator<?>> map = assertions.getComparatorsForElementPropertyOrFieldTypes();34 }35}

Full Screen

Full Screen

getComparatorsForElementPropertyOrFieldTypes

Using AI Code Generation

copy

Full Screen

1package com.example;2import org.assertj.core.api.AbstractObjectArrayAssert;3import org.assertj.core.api.Assertions;4import java.util.Comparator;5import java.util.List;6public class Example {7 public static void main(String[] args) {8 AbstractObjectArrayAssert<?, ?> assertions = Assertions.assertThat(new Object[] { "a", "b", "c" });9 List<Comparator<Object>> comparators = assertions.getComparatorsForElementPropertyOrFieldTypes(String.class);10 System.out.println(comparators);11 }12}

Full Screen

Full Screen

getComparatorsForElementPropertyOrFieldTypes

Using AI Code Generation

copy

Full Screen

1package com.javacodegeeks;2import java.util.Comparator;3import org.assertj.core.api.Assertions;4import org.assertj.core.api.ObjectArrayAssert;5public class GetComparatorsForElementPropertyOrFieldTypes {6 public static void main(String[] args) {7 Object[] array = { new Employee("John", 25), new Employee("Mary", 30) };8 ObjectArrayAssert<Object> objectArrayAssert = Assertions.assertThat(array);9 Comparator<?>[] comparators = objectArrayAssert.getComparatorsForElementPropertyOrFieldTypes();10 System.out.println("Comparators for the element property or field types are: ");11 for (Comparator<?> comparator : comparators) {12 System.out.println(comparator);13 }14 }15}

Full Screen

Full Screen

getComparatorsForElementPropertyOrFieldTypes

Using AI Code Generation

copy

Full Screen

1import org.assertj.core.api.AbstractObjectArrayAssert;2import org.assertj.core.api.Assertions;3public class Demo {4 public static void main(String[] args) {5 AbstractObjectArrayAssert<?, ?> objArray = Assertions.assertThat(new Object[] { "A", "B" });6 objArray.getComparatorsForElementPropertyOrFieldTypes("Type");7 }8}9 at org.assertj.core.api.AbstractObjectArrayAssert.getComparatorsForElementPropertyOrFieldTypes(AbstractObjectArrayAssert.java:100)10 at Demo.main(Demo.java:10)

Full Screen

Full Screen

getComparatorsForElementPropertyOrFieldTypes

Using AI Code Generation

copy

Full Screen

1import org.assertj.core.api.Assertions;2import org.assertj.core.api.AbstractObjectArrayAssert;3public class Test {4 public static void main(String[] args) {5 Assertions.assertThat(new Object[] { "A", "B" }).usingElementComparatorOnFields("A").contains("A", "B");6 Assertions.assertThat(new Object[] { "A", "B" }).usingElementComparatorOnFields("A", "B").contains("A", "B");7 Assertions.assertThat(new Object[] { "A", "B" }).usingElementComparatorOnFields("A", "B", "C").contains("A", "B");8 Assertions.assertThat(new Object[] { "A", "B" }).usingElementComparatorOnFields("A", "B", "C", "D").contains("A", "B");9 Assertions.assertThat(new Object[] { "A", "B" }).usingElementComparatorOnFields("A", "B", "C", "D", "E").contains("A", "B");10 Assertions.assertThat(new Object[] { "A", "B" }).usingElementComparatorOnFields("A", "B", "C", "D", "E", "F").contains("A", "B");11 }12}13import org.assertj.core.api.Assertions;14import org.assertj.core.api.AbstractObjectArrayAssert;15public class Test {16 public static void main(String[] args) {17 Assertions.assertThat(new Object[] { "A", "B" }).usingElementComparatorOnFields("A").contains("A", "B");18 Assertions.assertThat(new Object[] { "A", "B" }).usingElementComparatorOnFields("A", "B").contains("A", "B");19 Assertions.assertThat(new Object[] { "A", "B" }).usingElementComparatorOnFields("A", "B", "C").contains("A", "B");20 Assertions.assertThat(new Object[] { "A", "B" }).usingElementComparatorOnFields("A", "B", "C", "D").contains("A", "B");21 Assertions.assertThat(new Object[] { "A", "B" }).usingElementComparatorOnFields("A", "B", "C", "D", "E").contains("A", "B");22 Assertions.assertThat(new Object[] {

Full Screen

Full Screen

getComparatorsForElementPropertyOrFieldTypes

Using AI Code Generation

copy

Full Screen

1import org.assertj.core.api.*;2import org.assertj.core.api.Assertions;3import org.assertj.core.util.introspection.IntrospectionError;4public class AssertjCore1 {5 public static void main(String[] args) {6 Object[] arr = { "a", "b", "c" };7 ObjectArrayAssert<Object> assertObj = Assertions.assertThat(arr);8 try {9 assertObj.getComparatorsForElementPropertyOrFieldTypes();10 System.out.println("Comparators for element property or field types are: " + assertObj.getComparatorsForElementPropertyOrFieldTypes());11 } catch (IntrospectionError e) {12 e.printStackTrace();13 }14 }15}16Java | Get Comparator for Element Property or Field Type using getComparatorForElementPropertyOrFieldType(String)17Java | Get Comparator for Element Property or Field Type using getComparatorForElementPropertyOrFieldType(Class)18Java | Get Comparator for Element Property or Field Type using getComparatorForElementPropertyOrFieldType(Class, String)19Java | Get Comparator for Element Property or Field Type using getComparatorForElementPropertyOrFieldType(String, String)20Java | Get Comparator for Element Property or Field Type using getComparatorForElementPropertyOrFieldType(Class, String, String)21Java | Get Comparator for Element Property or Field Type using getComparatorForElementPropertyOrFieldType(String, String, String)22Java | Get Comparator for Element Property or Field Type using getComparatorForElementPropertyOrFieldType(Class, String, String, String)23Java | Get Comparator for Element Property or Field Type using getComparatorForElementPropertyOrFieldType(String, String, String, String)24Java | Get Comparator for Element Property or Field Type using getComparatorForElementPropertyOrFieldType(Class, String, String, String, String)25Java | Get Comparator for Element Property or Field Type using getComparatorForElementPropertyOrFieldType(String, String, String, String, String)26public class Demo {27 public static void main(String[] args) {28 AbstractObjectArrayAssert<?, ?> objArray = Assertions.assertThat(new Object[] { "A", "B" });29 objArray.getComparatorsForElementPropertyOrFieldTypes("Type");30 }31}32 at org.assertj.core.api.AbstractObjectArrayAssert.getComparatorsForElementPropertyOrFieldTypes(AbstractObjectArrayAssert.java:100)33 at Demo.main(Demo.java:10)

Full Screen

Full Screen

getComparatorsForElementPropertyOrFieldTypes

Using AI Code Generation

copy

Full Screen

1import org.assertj.core.api.Assertions;2import org.assertj.core.api.AbstractObjectArrayAssert;3public class Test {4 public static void main(String[] args) {5 Assertions.assertThat(new Object[] { "A", "B" }).usingElementComparatorOnFields("A").contains("A", "B");6 Assertions.assertThat(new Object[] { "A", "B" }).usingElementComparatorOnFields("A", "B").contains("A", "B");7 Assertions.assertThat(new Object[] { "A", "B" }).usingElementComparatorOnFields("A", "B", "C").contains("A", "B");8 Assertions.assertThat(new Object[] { "A", "B" }).usingElementComparatorOnFields("A", "B", "C", "D").contains("A", "B");9 Assertions.assertThat(new Object[] { "A", "B" }).usingElementComparatorOnFields("A", "B", "C", "D", "E").contains("A", "B");10 Assertions.assertThat(new Object[] { "A", "B" }).usingElementComparatorOnFields("A", "B", "C", "D", "E", "F").contains("A", "B");11 }12}13import org.assertj.core.api.Assertions;14import org.assertj.core.api.AbstractObjectArrayAssert;15public class Test {16 public static void main(String[] args) {17 Assertions.assertThat(new Object[] { "A", "B" }).usingElementComparatorOnFields("A").contains("A", "B");18 Assertions.assertThat(new Object[] { "A", "B" }).usingElementComparatorOnFields("A", "B").contains("A", "B");19 Assertions.assertThat(new Object[] { "A", "B" }).usingElementComparatorOnFields("A", "B", "C").contains("A", "B");20 Assertions.assertThat(new Object[] { "A", "B" }).usingElementComparatorOnFields("A", "B", "C", "D").contains("A", "B");21 Assertions.assertThat(new Object[] { "A", "B" }).usingElementComparatorOnFields("A", "B", "C", "D", "E").contains("A", "B");22 Assertions.assertThat(new Object[] { of org.assertj.core.api.AbstractObjectAssert class

Full Screen

Full Screen

getComparatorsForElementPropertyOrFieldTypes

Using AI Code Generation

copy

Full Screen

1import org.assertj.core.api.AbstractObjectArrayAssert;2import org.assertj.core.api.Assertions;3public class Demo {4 public static void main(String[] args) {5 AbstractObjectArrayAssert<?, ?> objArray = Assertions.assertThat(new Object[] { "A", "B" });6 objArray.getComparatorsForElementPropertyOrFieldTypes("Type");7 }8}9 at org.assertj.core.api.AbstractObjectArrayAssert.getComparatorsForElementPropertyOrFieldTypes(AbstractObjectArrayAssert.java:100)10 at Demo.main(Demo.java:10)

Full Screen

Full Screen

getComparatorsForElementPropertyOrFieldTypes

Using AI Code Generation

copy

Full Screen

1import org.assertj.core.api.Assertions;2import org.assertj.core.api.AbstractObjectArrayAssert;3public class Test {4 public static void main(String[] args) {5 Assertions.assertThat(new Object[] { "A", "B" }).usingElementComparatorOnFields("A").contains("A", "B");6 Assertions.assertThat(new Object[] { "A", "B" }).usingElementComparatorOnFields("A", "B").contains("A", "B");7 Assertions.assertThat(new Object[] { "A", "B" }).usingElementComparatorOnFields("A", "B", "C").contains("A", "B");8 Assertions.assertThat(new Object[] { "A", "B" }).usingElementComparatorOnFields("A", "B", "C", "D").contains("A", "B");9 Assertions.assertThat(new Object[] { "A", "B" }).usingElementComparatorOnFields("A", "B", "C", "D", "E").contains("A", "B");10 Assertions.assertThat(new Object[] { "A", "B" }).usingElementComparatorOnFields("A", "B", "C", "D", "E", "F").contains("A", "B");11 }12}13import org.assertj.core.api.Assertions;14import org.assertj.core.api.AbstractObjectArrayAssert;15public class Test {16 public static void main(String[] args) {17 Assertions.assertThat(new Object[] { "A", "B" }).usingElementComparatorOnFields("A").contains("A", "B");18 Assertions.assertThat(new Object[] { "A", "B" }).usingElementComparatorOnFields("A", "B").contains("A", "B");19 Assertions.assertThat(new Object[] { "A", "B" }).usingElementComparatorOnFields("A", "B", "C").contains("A", "B");20 Assertions.assertThat(new Object[] { "A", "B" }).usingElementComparatorOnFields("A", "B", "C", "D").contains("A", "B");21 Assertions.assertThat(new Object[] { "A", "B" }).usingElementComparatorOnFields("A", "B", "C", "D", "E").contains("A", "B");22 Assertions.assertThat(new Object[] {

Full Screen

Full Screen

Automation Testing Tutorials

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

LambdaTest Learning Hubs:

YouTube

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

Run Assertj automation tests on LambdaTest cloud grid

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

Most used method in AbstractObjectArrayAssert

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful