How to use clone method of org.assertj.core.internal.Maps class

Best Assertj code snippet using org.assertj.core.internal.Maps.clone

Source:AbstractIterableAssert.java Github

copy

Full Screen

1/**2 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with3 * the License. You may obtain a copy of the License at4 *5 * http://www.apache.org/licenses/LICENSE-2.06 *7 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on8 * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the9 * specific language governing permissions and limitations under the License.10 *11 * Copyright 2012-2017 the original author or authors.12 */13package org.assertj.core.api;14import static org.assertj.core.api.Assertions.assertThat;15import static org.assertj.core.api.filter.Filters.filter;16import static org.assertj.core.description.Description.mostRelevantDescription;17import static org.assertj.core.extractor.Extractors.byName;18import static org.assertj.core.extractor.Extractors.extractedDescriptionOf;19import static org.assertj.core.extractor.Extractors.extractedDescriptionOfMethod;20import static org.assertj.core.extractor.Extractors.resultOf;21import static org.assertj.core.internal.CommonValidations.checkSequenceIsNotNull;22import static org.assertj.core.internal.CommonValidations.checkSubsequenceIsNotNull;23import static org.assertj.core.internal.TypeComparators.defaultTypeComparators;24import static org.assertj.core.util.Arrays.isArray;25import static org.assertj.core.util.IterableUtil.toArray;26import static org.assertj.core.util.Lists.newArrayList;27import static org.assertj.core.util.Preconditions.checkNotNull;28import java.lang.reflect.Array;29import java.util.Arrays;30import java.util.Collection;31import java.util.Comparator;32import java.util.HashSet;33import java.util.Iterator;34import java.util.List;35import java.util.Map;36import java.util.TreeMap;37import org.assertj.core.api.IterableAssert.LazyIterable;38import org.assertj.core.api.filter.FilterOperator;39import org.assertj.core.api.filter.Filters;40import org.assertj.core.api.iterable.Extractor;41import org.assertj.core.condition.Not;42import org.assertj.core.description.Description;43import org.assertj.core.extractor.Extractors;44import org.assertj.core.groups.FieldsOrPropertiesExtractor;45import org.assertj.core.groups.Tuple;46import org.assertj.core.internal.CommonErrors;47import org.assertj.core.internal.ComparatorBasedComparisonStrategy;48import org.assertj.core.internal.ComparisonStrategy;49import org.assertj.core.internal.ExtendedByTypesComparator;50import org.assertj.core.internal.FieldByFieldComparator;51import org.assertj.core.internal.IgnoringFieldsComparator;52import org.assertj.core.internal.IterableElementComparisonStrategy;53import org.assertj.core.internal.Iterables;54import org.assertj.core.internal.ObjectArrays;55import org.assertj.core.internal.Objects;56import org.assertj.core.internal.OnFieldsComparator;57import org.assertj.core.internal.RecursiveFieldByFieldComparator;58import org.assertj.core.internal.TypeComparators;59import org.assertj.core.util.CheckReturnValue;60import org.assertj.core.util.IterableUtil;61import org.assertj.core.util.Preconditions;62import org.assertj.core.util.Strings;63import org.assertj.core.util.introspection.IntrospectionError;64/**65 * Base class for implementations of <code>{@link ObjectEnumerableAssert}</code> whose actual value type is66 * <code>{@link Collection}</code>.67 *68 * @param <SELF> the "self" type of this assertion class. Please read &quot;<a href="http://bit.ly/1IZIRcY"69 * target="_blank">Emulating 'self types' using Java Generics to simplify fluent API implementation</a>&quot;70 * for more details.71 * @param <ACTUAL> the type of the "actual" value.72 * @param <ELEMENT> the type of elements of the "actual" value.73 * @param <ELEMENT_ASSERT> used for navigational assertions to return the right assert type.74 *75 * @author Yvonne Wang76 * @author Alex Ruiz77 * @author Mathieu Baechler78 * @author Joel Costigliola79 * @author Maciej Jaskowski80 * @author Nicolas François81 * @author Mikhail Mazursky82 * @author Mateusz Haligowski83 * @author Lovro Pandzic84 * @author Marko Bekhta85 */86//@format:off87public abstract class AbstractIterableAssert<SELF extends AbstractIterableAssert<SELF, ACTUAL, ELEMENT, ELEMENT_ASSERT>,88 ACTUAL extends Iterable<? extends ELEMENT>,89 ELEMENT,90 ELEMENT_ASSERT extends AbstractAssert<ELEMENT_ASSERT, ELEMENT>>91 extends AbstractAssert<SELF, ACTUAL>92 implements ObjectEnumerableAssert<SELF, ELEMENT> {93//@format:on94 private static final String ASSERT = "Assert";95 private TypeComparators comparatorsByType = defaultTypeComparators();96 private Map<String, Comparator<?>> comparatorsForElementPropertyOrFieldNames = new TreeMap<>();97 private TypeComparators comparatorsForElementPropertyOrFieldTypes = defaultTypeComparators();98 protected Iterables iterables = Iterables.instance();99 public AbstractIterableAssert(ACTUAL actual, Class<?> selfType) {100 super(actual, selfType);101 }102 protected static <T> Iterable<T> toLazyIterable(Iterator<T> actual) {103 if (actual == null) {104 return null;105 }106 return new LazyIterable<>(actual);107 }108 /**109 * Create a friendly soft or "hard" assertion.110 * <p>111 * Implementations need to redefine it so that some methods, such as {@link #extracting(Extractor)}, are able112 * to build the appropriate list assert (eg: {@link ListAssert} versus {@link SoftAssertionListAssert}).113 * <p>114 * The default implementation will assume that this concrete implementation is NOT a soft assertion.115 *116 * @param newActual new value117 * @return a new {@link AbstractListAssert}.118 */119 protected <E> AbstractListAssert<?, List<? extends E>, E, ObjectAssert<E>> newListAssertInstance(List<? extends E> newActual) {120 // this might not be the best implementation (SoftAssertion needs to override this).121 return new ListAssert<>(newActual);122 }123 /**124 * {@inheritDoc}125 */126 @Override127 public void isNullOrEmpty() {128 iterables.assertNullOrEmpty(info, actual);129 }130 /**131 * {@inheritDoc}132 */133 @Override134 public void isEmpty() {135 iterables.assertEmpty(info, actual);136 }137 /**138 * {@inheritDoc}139 */140 @Override141 public SELF isNotEmpty() {142 iterables.assertNotEmpty(info, actual);143 return myself;144 }145 /**146 * {@inheritDoc}147 */148 @Override149 public SELF hasSize(int expected) {150 iterables.assertHasSize(info, actual, expected);151 return myself;152 }153 /**154 * {@inheritDoc}155 */156 @Override157 public SELF hasSameSizeAs(Object other) {158 iterables.assertHasSameSizeAs(info, actual, other);159 return myself;160 }161 /**162 * {@inheritDoc}163 */164 @Override165 public SELF hasSameSizeAs(Iterable<?> other) {166 iterables.assertHasSameSizeAs(info, actual, other);167 return myself;168 }169 /**170 * {@inheritDoc}171 */172 @Override173 public SELF contains(@SuppressWarnings("unchecked") ELEMENT... values) {174 iterables.assertContains(info, actual, values);175 return myself;176 }177 /**178 * {@inheritDoc}179 */180 @Override181 public SELF containsOnly(@SuppressWarnings("unchecked") ELEMENT... values) {182 iterables.assertContainsOnly(info, actual, values);183 return myself;184 }185 /**186 * {@inheritDoc}187 */188 @Override189 public SELF containsOnlyOnce(@SuppressWarnings("unchecked") ELEMENT... values) {190 iterables.assertContainsOnlyOnce(info, actual, values);191 return myself;192 }193 /**194 * {@inheritDoc}195 */196 @Override197 public SELF containsOnlyNulls() {198 iterables.assertContainsOnlyNulls(info, actual);199 return myself;200 }201 /**202 * {@inheritDoc}203 */204 @Override205 public SELF containsExactly(@SuppressWarnings("unchecked") ELEMENT... values) {206 iterables.assertContainsExactly(info, actual, values);207 return myself;208 }209 /** {@inheritDoc} */210 @Override211 public SELF containsExactlyInAnyOrder(@SuppressWarnings("unchecked") ELEMENT... values) {212 iterables.assertContainsExactlyInAnyOrder(info, actual, values);213 return myself;214 }215 /**216 * {@inheritDoc}217 */218 @Override219 public SELF containsExactlyInAnyOrderElementsOf(Iterable<? extends ELEMENT> values) {220 return containsExactlyInAnyOrder(toArray(values));221 }222 /**223 * {@inheritDoc}224 */225 @Override226 public SELF isSubsetOf(Iterable<? extends ELEMENT> values) {227 iterables.assertIsSubsetOf(info, actual, values);228 return myself;229 }230 /**231 * {@inheritDoc}232 */233 @Override234 public SELF isSubsetOf(@SuppressWarnings("unchecked") ELEMENT... values) {235 iterables.assertIsSubsetOf(info, actual, Arrays.asList(values));236 return myself;237 }238 /**239 * {@inheritDoc}240 */241 @Override242 public SELF containsSequence(@SuppressWarnings("unchecked") ELEMENT... sequence) {243 iterables.assertContainsSequence(info, actual, sequence);244 return myself;245 }246 /**247 * {@inheritDoc}248 */249 @Override250 public SELF containsSequence(Iterable<? extends ELEMENT> sequence) {251 checkSequenceIsNotNull(sequence);252 iterables.assertContainsSequence(info, actual, toArray(sequence));253 return myself;254 }255 /**256 * {@inheritDoc}257 */258 @Override259 public SELF doesNotContainSequence(@SuppressWarnings("unchecked") ELEMENT... sequence) {260 iterables.assertDoesNotContainSequence(info, actual, sequence);261 return myself;262 }263 /**264 * {@inheritDoc}265 */266 @Override267 public SELF doesNotContainSequence(Iterable<? extends ELEMENT> sequence) {268 checkSequenceIsNotNull(sequence);269 iterables.assertDoesNotContainSequence(info, actual, toArray(sequence));270 return myself;271 }272 /**273 * {@inheritDoc}274 */275 @Override276 public SELF containsSubsequence(@SuppressWarnings("unchecked") ELEMENT... subsequence) {277 iterables.assertContainsSubsequence(info, actual, subsequence);278 return myself;279 }280 /**281 * {@inheritDoc}282 */283 @Override284 public SELF containsSubsequence(Iterable<? extends ELEMENT> subsequence) {285 checkSubsequenceIsNotNull(subsequence);286 iterables.assertContainsSubsequence(info, actual, toArray(subsequence));287 return myself;288 }289 /**290 * {@inheritDoc}291 */292 @Override293 public SELF doesNotContainSubsequence(@SuppressWarnings("unchecked") ELEMENT... subsequence) {294 iterables.assertDoesNotContainSubsequence(info, actual, subsequence);295 return myself;296 }297 /**298 * {@inheritDoc}299 */300 @Override301 public SELF doesNotContainSubsequence(Iterable<? extends ELEMENT> subsequence) {302 checkSubsequenceIsNotNull(subsequence);303 iterables.assertDoesNotContainSubsequence(info, actual, toArray(subsequence));304 return myself;305 }306 @Override307 public SELF doesNotContain(@SuppressWarnings("unchecked") ELEMENT... values) {308 iterables.assertDoesNotContain(info, actual, values);309 return myself;310 }311 @Override312 public SELF doesNotContainAnyElementsOf(Iterable<? extends ELEMENT> iterable) {313 iterables.assertDoesNotContainAnyElementsOf(info, actual, iterable);314 return myself;315 }316 /**317 * {@inheritDoc}318 */319 @Override320 public SELF doesNotHaveDuplicates() {321 iterables.assertDoesNotHaveDuplicates(info, actual);322 return myself;323 }324 /**325 * {@inheritDoc}326 */327 @Override328 public SELF startsWith(@SuppressWarnings("unchecked") ELEMENT... sequence) {329 iterables.assertStartsWith(info, actual, sequence);330 return myself;331 }332 /**333 * {@inheritDoc}334 */335 @Override336 public SELF endsWith(ELEMENT first, @SuppressWarnings("unchecked") ELEMENT... rest) {337 iterables.assertEndsWith(info, actual, first, rest);338 return myself;339 }340 /**341 * {@inheritDoc}342 */343 @Override344 public SELF endsWith(ELEMENT[] sequence) {345 iterables.assertEndsWith(info, actual, sequence);346 return myself;347 }348 /**349 * {@inheritDoc}350 */351 @Override352 public SELF containsNull() {353 iterables.assertContainsNull(info, actual);354 return myself;355 }356 /**357 * {@inheritDoc}358 */359 @Override360 public SELF doesNotContainNull() {361 iterables.assertDoesNotContainNull(info, actual);362 return myself;363 }364 /**365 * {@inheritDoc}366 */367 @Override368 public SELF are(Condition<? super ELEMENT> condition) {369 iterables.assertAre(info, actual, condition);370 return myself;371 }372 /**373 * {@inheritDoc}374 */375 @Override376 public SELF areNot(Condition<? super ELEMENT> condition) {377 iterables.assertAreNot(info, actual, condition);378 return myself;379 }380 /**381 * {@inheritDoc}382 */383 @Override384 public SELF have(Condition<? super ELEMENT> condition) {385 iterables.assertHave(info, actual, condition);386 return myself;387 }388 /**389 * {@inheritDoc}390 */391 @Override392 public SELF doNotHave(Condition<? super ELEMENT> condition) {393 iterables.assertDoNotHave(info, actual, condition);394 return myself;395 }396 /**397 * {@inheritDoc}398 */399 @Override400 public SELF areAtLeastOne(Condition<? super ELEMENT> condition) {401 areAtLeast(1, condition);402 return myself;403 }404 /**405 * {@inheritDoc}406 */407 @Override408 public SELF areAtLeast(int times, Condition<? super ELEMENT> condition) {409 iterables.assertAreAtLeast(info, actual, times, condition);410 return myself;411 }412 /**413 * {@inheritDoc}414 */415 @Override416 public SELF areAtMost(int times, Condition<? super ELEMENT> condition) {417 iterables.assertAreAtMost(info, actual, times, condition);418 return myself;419 }420 /**421 * {@inheritDoc}422 */423 @Override424 public SELF areExactly(int times, Condition<? super ELEMENT> condition) {425 iterables.assertAreExactly(info, actual, times, condition);426 return myself;427 }428 /** {@inheritDoc} */429 @Override430 public SELF haveAtLeastOne(Condition<? super ELEMENT> condition) {431 return haveAtLeast(1, condition);432 }433 /**434 * {@inheritDoc}435 */436 @Override437 public SELF haveAtLeast(int times, Condition<? super ELEMENT> condition) {438 iterables.assertHaveAtLeast(info, actual, times, condition);439 return myself;440 }441 /**442 * {@inheritDoc}443 */444 @Override445 public SELF haveAtMost(int times, Condition<? super ELEMENT> condition) {446 iterables.assertHaveAtMost(info, actual, times, condition);447 return myself;448 }449 /**450 * {@inheritDoc}451 */452 @Override453 public SELF haveExactly(int times, Condition<? super ELEMENT> condition) {454 iterables.assertHaveExactly(info, actual, times, condition);455 return myself;456 }457 /**458 * Verifies that at least one element in the actual {@code Iterable} has the specified type (matching includes459 * subclasses of the given type).460 * <p>461 * Example:462 * <pre><code class='java'> List&lt;Number&gt; numbers = new ArrayList&lt;Number&gt;();463 * numbers.add(1);464 * numbers.add(2L);465 *466 * // successful assertion:467 * assertThat(numbers).hasAtLeastOneElementOfType(Long.class);468 *469 * // assertion failure:470 * assertThat(numbers).hasAtLeastOneElementOfType(Float.class);</code></pre>471 *472 * @param expectedType the expected type.473 * @return this assertion object.474 * @throws NullPointerException if the given type is {@code null}.475 * @throws AssertionError if the actual {@code Object} group does not have any elements of the given type.476 */477 @Override478 public SELF hasAtLeastOneElementOfType(Class<?> expectedType) {479 // reuse code from object arrays as the logic is the same480 // (ok since this assertion doesn't rely on a comparison strategy)481 ObjectArrays.instance().assertHasAtLeastOneElementOfType(info, toArray(actual), expectedType);482 return myself;483 }484 /**485 * Verifies that all elements in the actual {@code Iterable} have the specified type (matching includes486 * subclasses of the given type).487 * <p>488 * Example:489 * <pre><code class='java'> List&lt;Number&gt; numbers = new ArrayList&lt;Number&gt;();490 * numbers.add(1);491 * numbers.add(2);492 * numbers.add(3);493 *494 * // successful assertions:495 * assertThat(numbers).hasOnlyElementsOfType(Number.class);496 * assertThat(numbers).hasOnlyElementsOfType(Integer.class);497 *498 * // assertion failure:499 * assertThat(numbers).hasOnlyElementsOfType(Long.class);</code></pre>500 *501 * @param expectedType the expected type.502 * @return this assertion object.503 * @throws NullPointerException if the given type is {@code null}.504 * @throws AssertionError if one element is not of the expected type.505 */506 @Override507 public SELF hasOnlyElementsOfType(Class<?> expectedType) {508 // reuse code from object arrays as the logic is the same509 // (ok since this assertion doesn't rely on a comparison strategy)510 ObjectArrays.instance().assertHasOnlyElementsOfType(info, toArray(actual), expectedType);511 return myself;512 }513 /**514 * Verifies that all elements in the actual {@code Iterable} do not have the specified typetypes (including subclasses).515 * <p>516 * Example:517 * <pre><code class='java'> List&lt;Number&gt; numbers = new ArrayList&lt;&gt;();518 * numbers.add(1);519 * numbers.add(2);520 * numbers.add(3.0);521 *522 * // successful assertions:523 * assertThat(numbers).doesNotHaveAnyElementsOfTypes(Long.class, Float.class);524 *525 * // assertion failure:526 * assertThat(numbers).doesNotHaveAnyElementsOfTypes(Long.class, Integer.class);</code></pre>527 *528 * @param unexpectedTypes the not expected types.529 * @return this assertion object.530 * @throws NullPointerException if the given type is {@code null}.531 * @throws AssertionError if one element's type matches the given types.532 * @since 2.9.0 / 3.9.0533 */534 @Override535 public SELF doesNotHaveAnyElementsOfTypes(Class<?>... unexpectedTypes) {536 ObjectArrays.instance().assertDoesNotHaveAnyElementsOfTypes(info, toArray(actual), unexpectedTypes);537 return myself;538 }539 /** {@inheritDoc} */540 @Override541 public SELF hasOnlyElementsOfTypes(Class<?>... types) {542 ObjectArrays.instance().assertHasOnlyElementsOfTypes(info, toArray(actual), types);543 return myself;544 }545 /**546 * {@inheritDoc}547 */548 @Override549 public SELF containsAll(Iterable<? extends ELEMENT> iterable) {550 iterables.assertContainsAll(info, actual, iterable);551 return myself;552 }553 /**554 * {@inheritDoc}555 */556 @Override557 @CheckReturnValue558 public SELF usingElementComparator(Comparator<? super ELEMENT> elementComparator) {559 this.iterables = new Iterables(new ComparatorBasedComparisonStrategy(elementComparator));560 // to have the same semantics on base assertions like isEqualTo, we need to use an iterable comparator comparing561 // elements with elementComparator parameter562 objects = new Objects(new IterableElementComparisonStrategy<>(elementComparator));563 return myself;564 }565 @CheckReturnValue566 private SELF usingExtendedByTypesElementComparator(Comparator<Object> elementComparator) {567 return usingElementComparator(new ExtendedByTypesComparator(elementComparator, comparatorsByType));568 }569 /**570 * {@inheritDoc}571 */572 @Override573 @CheckReturnValue574 public SELF usingDefaultElementComparator() {575 usingDefaultComparator();576 this.iterables = Iterables.instance();577 return myself;578 }579 /**580 * Verifies that the actual {@link Iterable} contains at least one of the given values.581 * <p>582 * Example :583 * <pre><code class='java'> Iterable&lt;String&gt; abc = Arrays.asList("a", "b", "c");584 *585 * // assertions will pass586 * assertThat(abc).containsAnyOf("b")587 * .containsAnyOf("b", "c")588 * .containsAnyOf("a", "b", "c")589 * .containsAnyOf("a", "b", "c", "d")590 * .containsAnyOf("e", "f", "g", "b");591 *592 * // assertions will fail593 * assertThat(abc).containsAnyOf("d");594 * assertThat(abc).containsAnyOf("d", "e", "f", "g");</code></pre>595 *596 * @param values the values whose at least one which is expected to be in the {@code Iterable} under test.597 * @return {@code this} assertion object.598 * @throws NullPointerException if the array of values is {@code null}.599 * @throws IllegalArgumentException if the array of values is empty and the {@code Iterable} under test is not empty.600 * @throws AssertionError if the {@code Iterable} under test is {@code null}.601 * @throws AssertionError if the {@code Iterable} under test does not contain any of the given {@code values}.602 * @since 2.9.0 / 3.9.0603 */604 @Override605 public SELF containsAnyOf(@SuppressWarnings("unchecked") ELEMENT... values) {606 iterables.assertContainsAnyOf(info, actual, values);607 return myself;608 }609 /**610 * Verifies that the {@link Iterable} under test contains at least one of the given {@link Iterable} elements.611 * <p>612 * Example :613 * <pre><code class='java'> Iterable&lt;String&gt; abc = Arrays.asList("a", "b", "c");614 *615 * // assertions will pass616 * assertThat(abc).containsAnyElementsOf(Arrays.asList("b"))617 * .containsAnyElementsOf(Arrays.asList("b", "c"))618 * .containsAnyElementsOf(Arrays.asList("a", "b", "c"))619 * .containsAnyElementsOf(Arrays.asList("a", "b", "c", "d"))620 * .containsAnyElementsOf(Arrays.asList("e", "f", "g", "b"));621 *622 * // assertions will fail623 * assertThat(abc).containsAnyElementsOf(Arrays.asList("d"));624 * assertThat(abc).containsAnyElementsOf(Arrays.asList("d", "e", "f", "g"));</code></pre>625 *626 * @param iterable the iterable whose at least one element is expected to be in the {@code Iterable} under test.627 * @return {@code this} assertion object.628 * @throws NullPointerException if the iterable of expected values is {@code null}.629 * @throws IllegalArgumentException if the iterable of expected values is empty and the {@code Iterable} under test is not empty.630 * @throws AssertionError if the {@code Iterable} under test is {@code null}.631 * @throws AssertionError if the {@code Iterable} under test does not contain any of elements from the given {@code Iterable}.632 * @since 2.9.0 / 3.9.0633 */634 @Override635 public SELF containsAnyElementsOf(Iterable<ELEMENT> iterable) {636 return containsAnyOf(toArray(iterable));637 }638 /**639 * Extract the values of the given field or property from the Iterable's elements under test into a new Iterable, this new640 * Iterable becoming the Iterable under test.641 * <p>642 * It allows you to test a property/field of the the Iterable's elements instead of testing the elements themselves, which643 * can be be much less work !644 * <p>645 * Let's take a look at an example to make things clearer :646 * <pre><code class='java'> // build a list of TolkienCharacters: a TolkienCharacter has a name, and age and a Race (a specific class)647 * // they can be public field or properties, both can be extracted.648 * List&lt;TolkienCharacter&gt; fellowshipOfTheRing = new ArrayList&lt;TolkienCharacter&gt;();649 *650 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Frodo&quot;, 33, HOBBIT));651 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Sam&quot;, 38, HOBBIT));652 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Gandalf&quot;, 2020, MAIA));653 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Legolas&quot;, 1000, ELF));654 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Pippin&quot;, 28, HOBBIT));655 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Gimli&quot;, 139, DWARF));656 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Aragorn&quot;, 87, MAN);657 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Boromir&quot;, 37, MAN));658 *659 * // let's verify the names of the TolkienCharacters in fellowshipOfTheRing :660 *661 * assertThat(fellowshipOfTheRing).extracting(&quot;name&quot;)662 * .contains(&quot;Boromir&quot;, &quot;Gandalf&quot;, &quot;Frodo&quot;)663 * .doesNotContain(&quot;Sauron&quot;, &quot;Elrond&quot;);664 *665 * // you can extract nested properties/fields like the name of the race :666 *667 * assertThat(fellowshipOfTheRing).extracting(&quot;race.name&quot;)668 * .contains(&quot;Hobbit&quot;, &quot;Elf&quot;)669 * .doesNotContain(&quot;Orc&quot;);</code></pre>670 * <p>671 * A property with the given name is searched for first. If it doesn't exist a field with the given name is looked672 * for. If the field does not exist an {@link IntrospectionError} is thrown. By default private fields are read but673 * you can change this with {@link Assertions#setAllowComparingPrivateFields(boolean)}. Trying to read a private field674 * when it's not allowed leads to an {@link IntrospectionError}.675 * <p>676 * Note that the order of extracted property/field values is consistent with the iteration order of the Iterable under677 * test, for example if it's a {@link HashSet}, you won't be able to make any assumptions on the extracted values678 * order.679 * <hr>680 * <p>681 * Extracting also support maps, that is, instead of extracting values from an Object, it extracts maps values682 * corresponding to the given keys.683 * <p>684 * Example:685 * <pre><code class='java'> Employee yoda = new Employee(1L, new Name("Yoda"), 800);686 * Employee luke = new Employee(2L, new Name("Luke"), 22);687 * Employee han = new Employee(3L, new Name("Han"), 31);688 *689 * // build two maps690 * Map&lt;String, Employee&gt; map1 = new HashMap&lt;&gt;();691 * map1.put("key1", yoda);692 * map1.put("key2", luke);693 *694 * Map&lt;String, Employee&gt; map2 = new HashMap&lt;&gt;();695 * map2.put("key1", yoda);696 * map2.put("key2", han);697 *698 * // instead of a list of objects, we have a list of maps699 * List&lt;Map&lt;String, Employee&gt;&gt; maps = asList(map1, map2);700 *701 * // extracting a property in that case = get values from maps using the property as a key702 * assertThat(maps).extracting("key2").containsExactly(luke, han);703 * assertThat(maps).extracting("key1").containsExactly(yoda, yoda);704 *705 * // type safe version706 * assertThat(maps).extracting(key2, Employee.class).containsExactly(luke, han);707 *708 * // it works with several keys, extracted values being wrapped in a Tuple709 * assertThat(maps).extracting("key1", "key2").containsExactly(tuple(yoda, luke), tuple(yoda, han));710 *711 * // unknown keys leads to null (map behavior)712 * assertThat(maps).extracting("bad key").containsExactly(null, null);</code></pre>713 *714 * @param propertyOrField the property/field to extract from the elements of the Iterable under test715 * @return a new assertion object whose object under test is the list of extracted property/field values.716 * @throws IntrospectionError if no field or property exists with the given name in one of the initial717 * Iterable's element.718 */719 @CheckReturnValue720 public AbstractListAssert<?, List<? extends Object>, Object, ObjectAssert<Object>> extracting(String propertyOrField) {721 List<Object> values = FieldsOrPropertiesExtractor.extract(actual, byName(propertyOrField));722 String extractedDescription = extractedDescriptionOf(propertyOrField);723 String description = mostRelevantDescription(info.description(), extractedDescription);724 return newListAssertInstance(values).as(description);725 }726 /**727 * Extract the result of given method invocation on the Iterable's elements under test into a new Iterable, this new728 * Iterable becoming the Iterable under test.729 * <p>730 * It allows you to test the method results of the Iterable's elements instead of testing the elements themselves. This731 * is especially useful for classes that do not conform to the Java Bean's getter specification (i.e. public String732 * toString() or public String status() instead of public String getStatus()).733 * <p>734 * Let's take a look at an example to make things clearer :735 * <pre><code class='java'> // Build a array of WesterosHouse, a WesterosHouse has a method: public String sayTheWords()736 *737 * List&lt;WesterosHouse&gt; greatHouses = new ArrayList&lt;WesterosHouse&gt;();738 * greatHouses.add(new WesterosHouse(&quot;Stark&quot;, &quot;Winter is Coming&quot;));739 * greatHouses.add(new WesterosHouse(&quot;Lannister&quot;, &quot;Hear Me Roar!&quot;));740 * greatHouses.add(new WesterosHouse(&quot;Greyjoy&quot;, &quot;We Do Not Sow&quot;));741 * greatHouses.add(new WesterosHouse(&quot;Baratheon&quot;, &quot;Our is the Fury&quot;));742 * greatHouses.add(new WesterosHouse(&quot;Martell&quot;, &quot;Unbowed, Unbent, Unbroken&quot;));743 * greatHouses.add(new WesterosHouse(&quot;Tyrell&quot;, &quot;Growing Strong&quot;));744 *745 * // let's verify the words of the great houses of Westeros:746 * assertThat(greatHouses).extractingResultOf(&quot;sayTheWords&quot;)747 * .contains(&quot;Winter is Coming&quot;, &quot;We Do Not Sow&quot;, &quot;Hear Me Roar&quot;)748 * .doesNotContain(&quot;Lannisters always pay their debts&quot;);</code></pre>749 *750 * Following requirements have to be met to extract method results:751 * <ul>752 * <li>method has to be public,</li>753 * <li>method cannot accept any arguments,</li>754 * <li>method cannot return void.</li>755 * </ul>756 * <p>757 * Note that the order of extracted results is consistent with the iteration order of the Iterable under test, for758 * example if it's a {@link HashSet}, you won't be able to make any assumptions on the extracted results order.759 *760 * @param method the name of the method which result is to be extracted from the array under test761 * @return a new assertion object whose object under test is the Iterable of extracted values.762 * @throws IllegalArgumentException if no method exists with the given name, or method is not public, or method does763 * return void, or method accepts arguments.764 */765 @CheckReturnValue766 public AbstractListAssert<?, List<? extends Object>, Object, ObjectAssert<Object>> extractingResultOf(String method) {767 // can't refactor by calling extractingResultOf(method, Object.class) as SoftAssertion would fail768 List<Object> values = FieldsOrPropertiesExtractor.extract(actual, resultOf(method));769 String extractedDescription = extractedDescriptionOfMethod(method);770 String description = mostRelevantDescription(info.description(), extractedDescription);771 return newListAssertInstance(values).as(description);772 }773 /**774 * Extract the result of given method invocation on the Iterable's elements under test into a new list of the given775 * class, this new List becoming the object under test.776 * <p>777 * It allows you to test the method results of the Iterable's elements instead of testing the elements themselves, it778 * is especially useful for classes that do not conform to the Java Bean's getter specification (i.e. public String779 * toString() or public String status() instead of public String getStatus()).780 * <p>781 * Let's take an example to make things clearer :782 * <pre><code class='java'> // Build a array of WesterosHouse, a WesterosHouse has a method: public String sayTheWords()783 * List&lt;WesterosHouse&gt; greatHouses = new ArrayList&lt;WesterosHouse&gt;();784 * greatHouses.add(new WesterosHouse(&quot;Stark&quot;, &quot;Winter is Coming&quot;));785 * greatHouses.add(new WesterosHouse(&quot;Lannister&quot;, &quot;Hear Me Roar!&quot;));786 * greatHouses.add(new WesterosHouse(&quot;Greyjoy&quot;, &quot;We Do Not Sow&quot;));787 * greatHouses.add(new WesterosHouse(&quot;Baratheon&quot;, &quot;Our is the Fury&quot;));788 * greatHouses.add(new WesterosHouse(&quot;Martell&quot;, &quot;Unbowed, Unbent, Unbroken&quot;));789 * greatHouses.add(new WesterosHouse(&quot;Tyrell&quot;, &quot;Growing Strong&quot;));790 *791 * // let's verify the words of the great houses of Westeros:792 * assertThat(greatHouses).extractingResultOf(&quot;sayTheWords&quot;, String.class)793 * .contains(&quot;Winter is Coming&quot;, &quot;We Do Not Sow&quot;, &quot;Hear Me Roar&quot;)794 * .doesNotContain(&quot;Lannisters always pay their debts&quot;);</code></pre>795 *796 * Following requirements have to be met to extract method results:797 * <ul>798 * <li>method has to be public,</li>799 * <li>method cannot accept any arguments,</li>800 * <li>method cannot return void.</li>801 * </ul>802 * <p>803 * Note that the order of extracted property/field values is consistent with the iteration order of the Iterable under804 * test, for example if it's a {@link HashSet}, you won't be able to make any assumptions of the extracted values805 * order.806 *807 * @param method the name of the method which result is to be extracted from the array under test808 * @param extractedType type of element of the extracted List809 * @return a new assertion object whose object under test is the Iterable of extracted values.810 * @throws IllegalArgumentException if no method exists with the given name, or method is not public, or method does811 * return void or method accepts arguments.812 */813 @CheckReturnValue814 public <P> AbstractListAssert<?, List<? extends P>, P, ObjectAssert<P>> extractingResultOf(String method,815 Class<P> extractedType) {816 @SuppressWarnings("unchecked")817 List<P> values = (List<P>) FieldsOrPropertiesExtractor.extract(actual, resultOf(method));818 String extractedDescription = extractedDescriptionOfMethod(method);819 String description = mostRelevantDescription(info.description(), extractedDescription);820 return newListAssertInstance(values).as(description);821 }822 /**823 * Extract the values of given field or property from the Iterable's elements under test into a new Iterable, this new824 * Iterable becoming the Iterable under test.825 * <p>826 * It allows you to test a property/field of the the Iterable's elements instead of testing the elements themselves,827 * which can be much less work !828 * <p>829 * Let's take an example to make things clearer :830 * <pre><code class='java'> // Build a list of TolkienCharacter, a TolkienCharacter has a name, and age and a Race (a specific class)831 * // they can be public field or properties, both can be extracted.832 * List&lt;TolkienCharacter&gt; fellowshipOfTheRing = new ArrayList&lt;TolkienCharacter&gt;();833 *834 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Frodo&quot;, 33, HOBBIT));835 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Sam&quot;, 38, HOBBIT));836 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Gandalf&quot;, 2020, MAIA));837 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Legolas&quot;, 1000, ELF));838 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Pippin&quot;, 28, HOBBIT));839 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Gimli&quot;, 139, DWARF));840 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Aragorn&quot;, 87, MAN);841 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Boromir&quot;, 37, MAN));842 *843 * // let's verify the names of TolkienCharacter in fellowshipOfTheRing :844 * assertThat(fellowshipOfTheRing).extracting(&quot;name&quot;, String.class)845 * .contains(&quot;Boromir&quot;, &quot;Gandalf&quot;, &quot;Frodo&quot;)846 * .doesNotContain(&quot;Sauron&quot;, &quot;Elrond&quot;);847 *848 * // you can extract nested property/field like the name of Race :849 * assertThat(fellowshipOfTheRing).extracting(&quot;race.name&quot;, String.class)850 * .contains(&quot;Hobbit&quot;, &quot;Elf&quot;)851 * .doesNotContain(&quot;Orc&quot;);</code></pre>852 *853 * A property with the given name is looked for first, if it doesn't exist then a field with the given name is looked854 * for, if the field does not exist an {@link IntrospectionError} is thrown, by default private fields are read but855 * you can change this with {@link Assertions#setAllowComparingPrivateFields(boolean)}, trying to read a private field856 * when it's not allowed leads to an {@link IntrospectionError}.857 * <p>858 * Note that the order of extracted property/field values is consistent with the iteration order of the Iterable under859 * test, for example if it's a {@link HashSet}, you won't be able to make any assumptions on the extracted values860 * order.861 * <hr>862 * <p>863 * Extracting also support maps, that is, instead of extracting values from an Object, it extract maps values864 * corresponding to the given keys.865 * <p>866 * Example:867 * <pre><code class='java'> Employee yoda = new Employee(1L, new Name("Yoda"), 800);868 * Employee luke = new Employee(2L, new Name("Luke"), 22);869 * Employee han = new Employee(3L, new Name("Han"), 31);870 *871 * // build two maps872 * Map&lt;String, Employee&gt; map1 = new HashMap&lt;&gt;();873 * map1.put("key1", yoda);874 * map1.put("key2", luke);875 *876 * Map&lt;String, Employee&gt; map2 = new HashMap&lt;&gt;();877 * map2.put("key1", yoda);878 * map2.put("key2", han);879 *880 * // instead of a list of objects, we have a list of maps881 * List&lt;Map&lt;String, Employee&gt;&gt; maps = asList(map1, map2);882 *883 * // extracting a property in that case = get values from maps using property as a key884 * assertThat(maps).extracting(key2, Employee.class).containsExactly(luke, han);885 *886 * // non type safe version887 * assertThat(maps).extracting("key2").containsExactly(luke, han);888 * assertThat(maps).extracting("key1").containsExactly(yoda, yoda);889 *890 * // it works with several keys, extracted values being wrapped in a Tuple891 * assertThat(maps).extracting("key1", "key2").containsExactly(tuple(yoda, luke), tuple(yoda, han));892 *893 * // unknown keys leads to null (map behavior)894 * assertThat(maps).extracting("bad key").containsExactly(null, null);</code></pre>895 *896 * @param propertyOrField the property/field to extract from the Iterable under test897 * @param extractingType type to return898 * @return a new assertion object whose object under test is the list of extracted property/field values.899 * @throws IntrospectionError if no field or property exists with the given name in one of the initial900 * Iterable's element.901 */902 @CheckReturnValue903 public <P> AbstractListAssert<?, List<? extends P>, P, ObjectAssert<P>> extracting(String propertyOrField,904 Class<P> extractingType) {905 @SuppressWarnings("unchecked")906 List<P> values = (List<P>) FieldsOrPropertiesExtractor.extract(actual, byName(propertyOrField));907 String extractedDescription = extractedDescriptionOf(propertyOrField);908 String description = mostRelevantDescription(info.description(), extractedDescription);909 return newListAssertInstance(values).as(description);910 }911 /**912 * Extract the values of the given fields/properties from the Iterable's elements under test into a new Iterable composed913 * of Tuples (a simple data structure), this new Iterable becoming the Iterable under test.914 * <p>915 * It allows you to test fields/properties of the the Iterable's elements instead of testing the elements themselves,916 * which can be much less work!917 * <p>918 * The Tuple data corresponds to the extracted values of the given fields/properties, for instance if you ask to919 * extract "id", "name" and "email" then each Tuple data will be composed of id, name and email extracted from the920 * element of the initial Iterable (the Tuple's data order is the same as the given fields/properties order).921 * <p>922 * Let's take an example to make things clearer :923 * <pre><code class='java'> // Build a list of TolkienCharacter, a TolkienCharacter has a name, and age and a Race (a specific class)924 * // they can be public field or properties, both can be extracted.925 * List&lt;TolkienCharacter&gt; fellowshipOfTheRing = new ArrayList&lt;TolkienCharacter&gt;();926 *927 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Frodo&quot;, 33, HOBBIT));928 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Sam&quot;, 38, HOBBIT));929 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Gandalf&quot;, 2020, MAIA));930 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Legolas&quot;, 1000, ELF));931 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Pippin&quot;, 28, HOBBIT));932 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Gimli&quot;, 139, DWARF));933 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Aragorn&quot;, 87, MAN);934 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Boromir&quot;, 37, MAN));935 *936 * // let's verify 'name' and 'age' of some TolkienCharacter in fellowshipOfTheRing :937 * assertThat(fellowshipOfTheRing).extracting(&quot;name&quot;, &quot;age&quot;)938 * .contains(tuple(&quot;Boromir&quot;, 37),939 * tuple(&quot;Sam&quot;, 38),940 * tuple(&quot;Legolas&quot;, 1000));941 *942 *943 * // extract 'name', 'age' and Race name values :944 * assertThat(fellowshipOfTheRing).extracting(&quot;name&quot;, &quot;age&quot;, &quot;race.name&quot;)945 * .contains(tuple(&quot;Boromir&quot;, 37, &quot;Man&quot;),946 * tuple(&quot;Sam&quot;, 38, &quot;Hobbit&quot;),947 * tuple(&quot;Legolas&quot;, 1000, &quot;Elf&quot;));</code></pre>948 *949 * A property with the given name is looked for first, if it doesn't exist then a field with the given name is looked950 * for, if the field does not exist an {@link IntrospectionError} is thrown, by default private fields are read but951 * you can change this with {@link Assertions#setAllowComparingPrivateFields(boolean)}, trying to read a private field952 * when it's not allowed leads to an {@link IntrospectionError}.953 * <p>954 * Note that the order of extracted property/field values is consistent with the iteration order of the Iterable under955 * test, for example if it's a {@link HashSet}, you won't be able to make any assumptions on the extracted values956 * order.957 * <hr>958 * <p>959 * Extracting also support maps, that is, instead of extracting values from an Object, it extract maps values960 * corresponding to the given keys.961 * <p>962 * Example:963 * <pre><code class='java'> Employee yoda = new Employee(1L, new Name("Yoda"), 800);964 * Employee luke = new Employee(2L, new Name("Luke"), 22);965 * Employee han = new Employee(3L, new Name("Han"), 31);966 *967 * // build two maps968 * Map&lt;String, Employee&gt; map1 = new HashMap&lt;&gt;();969 * map1.put("key1", yoda);970 * map1.put("key2", luke);971 *972 * Map&lt;String, Employee&gt; map2 = new HashMap&lt;&gt;();973 * map2.put("key1", yoda);974 * map2.put("key2", han);975 *976 * // instead of a list of objects, we have a list of maps977 * List&lt;Map&lt;String, Employee&gt;&gt; maps = asList(map1, map2);978 *979 * // extracting a property in that case = get values from maps using property as a key980 * assertThat(maps).extracting("key2").containsExactly(luke, han);981 * assertThat(maps).extracting("key1").containsExactly(yoda, yoda);982 *983 * // it works with several keys, extracted values being wrapped in a Tuple984 * assertThat(maps).extracting("key1", "key2").containsExactly(tuple(yoda, luke), tuple(yoda, han));985 *986 * // unknown keys leads to null (map behavior)987 * assertThat(maps).extracting("bad key").containsExactly(null, null);</code></pre>988 *989 * @param propertiesOrFields the properties/fields to extract from the elements of the Iterable under test990 * @return a new assertion object whose object under test is the list of Tuple with extracted properties/fields values991 * as data.992 * @throws IntrospectionError if one of the given name does not match a field or property in one of the initial993 * Iterable's element.994 */995 @CheckReturnValue996 public AbstractListAssert<?, List<? extends Tuple>, Tuple, ObjectAssert<Tuple>> extracting(String... propertiesOrFields) {997 List<Tuple> values = FieldsOrPropertiesExtractor.extract(actual, byName(propertiesOrFields));998 String extractedDescription = extractedDescriptionOf(propertiesOrFields);999 String description = mostRelevantDescription(info.description(), extractedDescription);1000 return newListAssertInstance(values).as(description);1001 }1002 /**1003 * Extract the values from Iterable's elements under test by applying an extracting function on them. The returned1004 * iterable becomes a new object under test.1005 * <p>1006 * It allows to test values from the elements in more safe way than by using {@link #extracting(String)}, as it1007 * doesn't utilize introspection.1008 * <p>1009 * Let's have a look at an example :1010 * <pre><code class='java'> // Build a list of TolkienCharacter, a TolkienCharacter has a name, and age and a Race (a specific class)1011 * // they can be public field or properties, both can be extracted.1012 * List&lt;TolkienCharacter&gt; fellowshipOfTheRing = new ArrayList&lt;TolkienCharacter&gt;();1013 *1014 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Frodo&quot;, 33, HOBBIT));1015 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Sam&quot;, 38, HOBBIT));1016 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Gandalf&quot;, 2020, MAIA));1017 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Legolas&quot;, 1000, ELF));1018 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Pippin&quot;, 28, HOBBIT));1019 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Gimli&quot;, 139, DWARF));1020 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Aragorn&quot;, 87, MAN);1021 * fellowshipOfTheRing.add(new TolkienCharacter(&quot;Boromir&quot;, 37, MAN));1022 *1023 * // this extracts the race1024 * Extractor&lt;TolkienCharacter, Race&gt; race = new Extractor&lt;TolkienCharacter, Race&gt;() {1025 * {@literal @}Override1026 * public Race extract(TolkienCharacter input) {1027 * return input.getRace();1028 * }1029 * }1030 *1031 * // fellowship has hobbitses, right, my presioussss?1032 * assertThat(fellowshipOfTheRing).extracting(race).contains(HOBBIT);</code></pre>1033 *1034 * Note that the order of extracted property/field values is consistent with the iteration order of the Iterable under1035 * test, for example if it's a {@link HashSet}, you won't be able to make any assumptions on the extracted values1036 * order.1037 *1038 * @param extractor the object transforming input object to desired one1039 * @return a new assertion object whose object under test is the list of values extracted1040 */1041 @CheckReturnValue1042 public <V> AbstractListAssert<?, List<? extends V>, V, ObjectAssert<V>> extracting(Extractor<? super ELEMENT, V> extractor) {1043 List<V> values = FieldsOrPropertiesExtractor.extract(actual, extractor);1044 return newListAssertInstance(values);1045 }1046 /**1047 * Extract the Iterable values from Iterable's elements under test by applying an Iterable extracting function on them1048 * and concatenating the result lists. The returned iterable becomes a new object under test.1049 * <p>1050 * It allows testing the results of extracting values that are represented by Iterables.1051 * <p>1052 * For example:1053 * <pre><code class='java'> CartoonCharacter bart = new CartoonCharacter("Bart Simpson");1054 * CartoonCharacter lisa = new CartoonCharacter("Lisa Simpson");1055 * CartoonCharacter maggie = new CartoonCharacter("Maggie Simpson");1056 * CartoonCharacter homer = new CartoonCharacter("Homer Simpson");1057 * homer.addChildren(bart, lisa, maggie);1058 *1059 * CartoonCharacter pebbles = new CartoonCharacter("Pebbles Flintstone");1060 * CartoonCharacter fred = new CartoonCharacter("Fred Flintstone");1061 * fred.getChildren().add(pebbles);1062 *1063 * Extractor&lt;CartoonCharacter, List&lt;CartoonCharacter&gt;&gt; childrenOf = new Extractor&lt;CartoonChildren, List&lt;CartoonChildren&gt;&gt;() {1064 * {@literal @}Override1065 * public List&lt;CartoonChildren&gt; extract(CartoonCharacter input) {1066 * return input.getChildren();1067 * }1068 * }1069 *1070 * List&lt;CartoonCharacter&gt; parents = newArrayList(homer, fred);1071 * // check children1072 * assertThat(parent).flatExtracting(childrenOf)1073 * .containsOnly(bart, lisa, maggie, pebbles);</code></pre>1074 *1075 * The order of extracted values is consisted with both the order of the collection itself, as well as the extracted1076 * collections.1077 *1078 * @param extractor the object transforming input object to an Iterable of desired ones1079 * @return a new assertion object whose object under test is the list of values extracted1080 */1081 @CheckReturnValue1082 public <V> AbstractListAssert<?, List<? extends V>, V, ObjectAssert<V>> flatExtracting(Extractor<? super ELEMENT, ? extends Collection<V>> extractor) {1083 List<V> result = newArrayList();1084 final List<? extends Collection<V>> extractedValues = FieldsOrPropertiesExtractor.extract(actual, extractor);1085 for (Collection<? extends V> iterable : extractedValues) {1086 result.addAll(iterable);1087 }1088 return newListAssertInstance(result);1089 }1090 /**1091 * Extract from Iterable's elements the Iterable/Array values corresponding to the given property/field name and1092 * concatenate them into a single list becoming the new object under test.1093 * <p>1094 * It allows testing the elements of extracting values that are represented by iterables or arrays.1095 * <p>1096 * For example:1097 * <pre><code class='java'> CartoonCharacter bart = new CartoonCharacter("Bart Simpson");1098 * CartoonCharacter lisa = new CartoonCharacter("Lisa Simpson");1099 * CartoonCharacter maggie = new CartoonCharacter("Maggie Simpson");1100 * CartoonCharacter homer = new CartoonCharacter("Homer Simpson");1101 * homer.addChildren(bart, lisa, maggie);1102 *1103 * CartoonCharacter pebbles = new CartoonCharacter("Pebbles Flintstone");1104 * CartoonCharacter fred = new CartoonCharacter("Fred Flintstone");1105 * fred.getChildren().add(pebbles);1106 *1107 * List&lt;CartoonCharacter&gt; parents = newArrayList(homer, fred);1108 * // check children1109 * assertThat(parents).flatExtracting("children")1110 * .containsOnly(bart, lisa, maggie, pebbles);</code></pre>1111 *1112 * The order of extracted values is consisted with both the order of the collection itself, as well as the extracted1113 * collections.1114 *1115 * @param fieldOrPropertyName the object transforming input object to an Iterable of desired ones1116 * @return a new assertion object whose object under test is the list of values extracted1117 * @throws IllegalArgumentException if one of the extracted property value was not an array or an iterable.1118 */1119 @CheckReturnValue1120 public AbstractListAssert<?, List<? extends Object>, Object, ObjectAssert<Object>> flatExtracting(String fieldOrPropertyName) {1121 List<Object> extractedValues = newArrayList();1122 List<?> extractedGroups = FieldsOrPropertiesExtractor.extract(actual, byName(fieldOrPropertyName));1123 for (Object group : extractedGroups) {1124 // expecting group to be an iterable or an array1125 if (isArray(group)) {1126 int size = Array.getLength(group);1127 for (int i = 0; i < size; i++) {1128 extractedValues.add(Array.get(group, i));1129 }1130 } else if (group instanceof Iterable) {1131 Iterable<?> iterable = (Iterable<?>) group;1132 for (Object value : iterable) {1133 extractedValues.add(value);1134 }1135 } else {1136 CommonErrors.wrongElementTypeForFlatExtracting(group);1137 }1138 }1139 return newListAssertInstance(extractedValues);1140 }1141 /**1142 * Extract the given properties/fields values from each {@code Iterable}'s element and1143 * flatten the extracted values in a list that is used as the new object under test.1144 * <p>1145 * Given 2 properties, if the extracted values were not flattened, instead having a simple list like :1146 * <pre>element1.value1, element1.value2, element2.value1, element2.value2, ... </pre>1147 * ... we would get a list of list :1148 * <pre>list(element1.value1, element1.value2), list(element2.value1, element2.value2), ... </pre>1149 * <p>1150 * Code example:1151 * <pre><code class='java'> // fellowshipOfTheRing is a List&lt;TolkienCharacter&gt;1152 *1153 * // values are extracted in order and flattened : age1, name1, age2, name2, age3 ...1154 * assertThat(fellowshipOfTheRing).flatExtracting("age", "name")1155 * .contains(33 ,"Frodo",1156 * 1000, "Legolas",1157 * 87, "Aragorn");</code></pre>1158 *1159 * @param fieldOrPropertyNames the field and/or property names to extract from each actual {@code Iterable}'s element1160 * @return a new assertion object whose object under test is a flattened list of all extracted values.1161 * @throws IllegalArgumentException if fieldOrPropertyNames vararg is null or empty1162 * @since 2.5.01163 */1164 @CheckReturnValue1165 public AbstractListAssert<?, List<? extends Object>, Object, ObjectAssert<Object>> flatExtracting(String... fieldOrPropertyNames) {1166 List<Object> extractedValues = newArrayList();1167 for (Tuple tuple : FieldsOrPropertiesExtractor.extract(actual, Extractors.byName(fieldOrPropertyNames))) {1168 extractedValues.addAll(tuple.toList());1169 }1170 return newListAssertInstance(extractedValues);1171 }1172 /**1173 * {@inheritDoc}1174 */1175 @Override1176 public SELF containsExactlyElementsOf(Iterable<? extends ELEMENT> iterable) {1177 return containsExactly(toArray(iterable));1178 }1179 /**1180 * {@inheritDoc}1181 */1182 @Override1183 public SELF containsOnlyElementsOf(Iterable<? extends ELEMENT> iterable) {1184 return containsOnly(toArray(iterable));1185 }1186 /**1187 * {@inheritDoc}1188 */1189 @Override1190 public SELF hasSameElementsAs(Iterable<? extends ELEMENT> iterable) {1191 return containsOnlyElementsOf(iterable);1192 }1193 /**1194 * Allows to set a comparator to compare properties or fields of elements with the given names.1195 * A typical usage is for comparing fields of numeric type at a given precision.1196 * <p>1197 * To be used, comparators need to be specified by this method <b>before</b> calling any of:1198 * <ul>1199 * <li>{@link #usingFieldByFieldElementComparator}</li>1200 * <li>{@link #usingElementComparatorOnFields}</li>1201 * <li>{@link #usingElementComparatorIgnoringFields}</li>1202 * <li>{@link #usingRecursiveFieldByFieldElementComparator}</li>1203 * </ul>1204 * <p>1205 * Comparators specified by this method have precedence over comparators specified by1206 * {@link #usingComparatorForElementFieldsWithType(Comparator, Class) usingComparatorForElementFieldsWithType}.1207 * <p>1208 * Example:1209 *1210 * <pre><code class='java'> public class TolkienCharacter {1211 * private String name;1212 * private double height;1213 * // constructor omitted1214 * }1215 *1216 * TolkienCharacter frodo = new TolkienCharacter(&quot;Frodo&quot;, 1.2);1217 * TolkienCharacter tallerFrodo = new TolkienCharacter(&quot;Frodo&quot;, 1.3);1218 * TolkienCharacter reallyTallFrodo = new TolkienCharacter(&quot;Frodo&quot;, 1.9);1219 *1220 * Comparator&lt;Double&gt; closeEnough = new Comparator&lt;Double&gt;() {1221 * double precision = 0.5;1222 * public int compare(Double d1, Double d2) {1223 * return Math.abs(d1 - d2) &lt;= precision ? 0 : 1;1224 * }1225 * };1226 *1227 * // assertions will pass1228 * assertThat(asList(frodo)).usingComparatorForElementFieldsWithNames(closeEnough, &quot;height&quot;)1229 * .usingFieldByFieldElementComparator()1230 * .contains(tallerFrodo);1231 *1232 * assertThat(asList(frodo)).usingComparatorForElementFieldsWithNames(closeEnough, &quot;height&quot;)1233 * .usingElementComparatorOnFields(&quot;height&quot;)1234 * .contains(tallerFrodo);1235 *1236 * assertThat(asList(frodo)).usingComparatorForElementFieldsWithNames(closeEnough, &quot;height&quot;)1237 * .usingElementComparatorIgnoringFields(&quot;name&quot;)1238 * .contains(tallerFrodo);1239 *1240 * assertThat(asList(frodo)).usingComparatorForElementFieldsWithNames(closeEnough, &quot;height&quot;)1241 * .usingRecursiveFieldByFieldElementComparator()1242 * .contains(tallerFrodo);1243 *1244 * // assertion will fail1245 * assertThat(asList(frodo)).usingComparatorForElementFieldsWithNames(closeEnough, &quot;height&quot;)1246 * .usingFieldByFieldElementComparator()1247 * .containsExactly(reallyTallFrodo);</code></pre>1248 *1249 * @param comparator the {@link java.util.Comparator} to use1250 * @param elementPropertyOrFieldNames the names of the properties and/or fields of the elements the comparator should be used for1251 * @return {@code this} assertions object1252 * @since 2.5.0 / 3.5.01253 */1254 @CheckReturnValue1255 public <T> SELF usingComparatorForElementFieldsWithNames(Comparator<T> comparator,1256 String... elementPropertyOrFieldNames) {1257 for (String elementPropertyOrField : elementPropertyOrFieldNames) {1258 comparatorsForElementPropertyOrFieldNames.put(elementPropertyOrField, comparator);1259 }1260 return myself;1261 }1262 /**1263 * Allows to set a specific comparator to compare properties or fields of elements with the given type.1264 * A typical usage is for comparing fields of numeric type at a given precision.1265 * <p>1266 * To be used, comparators need to be specified by this method <b>before</b> calling any of:1267 * <ul>1268 * <li>{@link #usingFieldByFieldElementComparator}</li>1269 * <li>{@link #usingElementComparatorOnFields}</li>1270 * <li>{@link #usingElementComparatorIgnoringFields}</li>1271 * <li>{@link #usingRecursiveFieldByFieldElementComparator}</li>1272 * </ul>1273 * <p>1274 * Comparators specified by {@link #usingComparatorForElementFieldsWithNames(Comparator, String...) usingComparatorForElementFieldsWithNames}1275 * have precedence over comparators specified by this method.1276 * <p>1277 * Example:1278 * <pre><code class='java'> public class TolkienCharacter {1279 * private String name;1280 * private double height;1281 * // constructor omitted1282 * }1283 * TolkienCharacter frodo = new TolkienCharacter(&quot;Frodo&quot;, 1.2);1284 * TolkienCharacter tallerFrodo = new TolkienCharacter(&quot;Frodo&quot;, 1.3);1285 * TolkienCharacter reallyTallFrodo = new TolkienCharacter(&quot;Frodo&quot;, 1.9);1286 *1287 * Comparator&lt;Double&gt; closeEnough = new Comparator&lt;Double&gt;() {1288 * double precision = 0.5;1289 * public int compare(Double d1, Double d2) {1290 * return Math.abs(d1 - d2) &lt;= precision ? 0 : 1;1291 * }1292 * };1293 *1294 * // assertions will pass1295 * assertThat(Arrays.asList(frodo)).usingComparatorForElementFieldsWithType(closeEnough, Double.class)1296 * .usingFieldByFieldElementComparator()1297 * .contains(tallerFrodo);1298 *1299 * assertThat(Arrays.asList(frodo)).usingComparatorForElementFieldsWithType(closeEnough, Double.class)1300 * .usingElementComparatorOnFields(&quot;height&quot;)1301 * .contains(tallerFrodo);1302 *1303 * assertThat(Arrays.asList(frodo)).usingComparatorForElementFieldsWithType(closeEnough, Double.class)1304 * .usingElementComparatorIgnoringFields(&quot;name&quot;)1305 * .contains(tallerFrodo);1306 *1307 * assertThat(Arrays.asList(frodo)).usingComparatorForElementFieldsWithType(closeEnough, Double.class)1308 * .usingRecursiveFieldByFieldElementComparator()1309 * .contains(tallerFrodo);1310 *1311 * // assertion will fail1312 * assertThat(Arrays.asList(frodo)).usingComparatorForElementFieldsWithType(closeEnough, Double.class)1313 * .usingFieldByFieldElementComparator()1314 * .contains(reallyTallFrodo);</code></pre>1315 *1316 * @param comparator the {@link java.util.Comparator} to use1317 * @param type the {@link java.lang.Class} of the type of the element fields the comparator should be used for1318 * @return {@code this} assertions object1319 * @since 2.5.0 / 3.5.01320 */1321 @CheckReturnValue1322 public <T> SELF usingComparatorForElementFieldsWithType(Comparator<T> comparator, Class<T> type) {1323 comparatorsForElementPropertyOrFieldTypes.put(type, comparator);1324 return myself;1325 }1326 /**1327 * Allows to set a specific comparator for the given type of elements or their fields.1328 * Extends {@link #usingComparatorForElementFieldsWithType} by applying comparator specified for given type1329 * to elements themselves, not only to their fields.1330 * <p>1331 * Usage of this method affects comparators set by next methods:1332 * <ul>1333 * <li>{@link #usingFieldByFieldElementComparator}</li>1334 * <li>{@link #usingElementComparatorOnFields}</li>1335 * <li>{@link #usingElementComparatorIgnoringFields}</li>1336 * <li>{@link #usingRecursiveFieldByFieldElementComparator}</li>1337 * </ul>1338 * <p>1339 * Example:1340 * <pre><code class='java'>1341 * // assertion will pass1342 * assertThat(asList("some", new BigDecimal("4.2")))1343 * .usingComparatorForType(BIG_DECIMAL_COMPARATOR, BigDecimal.class)1344 * .contains(new BigDecimal("4.20"));1345 * </code></pre>1346 * </p>1347 *1348 * @param comparator the {@link java.util.Comparator} to use1349 * @param type the {@link java.lang.Class} of the type of the element or element fields the comparator should be used for1350 * @return {@code this} assertions object1351 * @since 2.9.0 / 3.9.01352 */1353 @CheckReturnValue1354 public <T> SELF usingComparatorForType(Comparator<T> comparator, Class<T> type) {1355 if (iterables.getComparator() == null) {1356 usingElementComparator(new ExtendedByTypesComparator(comparatorsByType));1357 }1358 comparatorsForElementPropertyOrFieldTypes.put(type, comparator);1359 comparatorsByType.put(type, comparator);1360 return myself;1361 }1362 /**1363 * Use field/property by field/property comparison (including inherited fields/properties) instead of relying on1364 * actual type A <code>equals</code> method to compare group elements for incoming assertion checks. Private fields1365 * are included but this can be disabled using {@link Assertions#setAllowExtractingPrivateFields(boolean)}.1366 * <p>1367 * This can be handy if <code>equals</code> method of the objects to compare does not suit you.1368 * <p>1369 * Note that the comparison is <b>not</b> recursive, if one of the fields/properties is an Object, it will be compared1370 * to the other field/property using its <code>equals</code> method.1371 * <p>1372 * You can specify a custom comparator per name or type of element field with1373 * {@link #usingComparatorForElementFieldsWithNames(Comparator, String...)}1374 * and {@link #usingComparatorForElementFieldsWithType(Comparator, Class)}.1375 * <p>1376 * Example:1377 * <pre><code class='java'> TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT);1378 * TolkienCharacter frodoClone = new TolkienCharacter("Frodo", 33, HOBBIT);1379 *1380 * // Fail if equals has not been overridden in TolkienCharacter as equals default implementation only compares references1381 * assertThat(newArrayList(frodo)).contains(frodoClone);1382 *1383 * // frodo and frodoClone are equals when doing a field by field comparison.1384 * assertThat(newArrayList(frodo)).usingFieldByFieldElementComparator().contains(frodoClone);</code></pre>1385 *1386 * @return {@code this} assertion object.1387 */1388 @CheckReturnValue1389 public SELF usingFieldByFieldElementComparator() {1390 return usingExtendedByTypesElementComparator(new FieldByFieldComparator(comparatorsForElementPropertyOrFieldNames,1391 comparatorsForElementPropertyOrFieldTypes));1392 }1393 /**1394 * Use a recursive field/property by field/property comparison (including inherited fields/properties)1395 * instead of relying on actual type <code>equals</code> method to compare group elements for incoming1396 * assertion checks. This can be useful if actual's {@code equals} implementation does not suit you.1397 * <p>1398 * The recursive property/field comparison is <b>not</b> applied on fields having a custom {@code equals}1399 * implementation, i.e. the overridden {@code equals} method will be used instead of a field/property by field/property1400 * comparison.1401 * <p>1402 * The recursive comparison handles cycles.1403 * <p>1404 * You can specify a custom comparator per (nested) name or type of element field with1405 * {@link #usingComparatorForElementFieldsWithNames(Comparator, String...) usingComparatorForElementFieldsWithNames}1406 * and {@link #usingComparatorForElementFieldsWithType(Comparator, Class) usingComparatorForElementFieldsWithType}.1407 * <p>1408 * The objects to compare can be of different types but must have the same properties/fields. For example if actual1409 * object has a {@code name} String field, the other object must also have one.1410 * <p>1411 * If an object has a field and a property with the same name, the property value will be used over the field.1412 * <p>1413 * Example:1414 * <pre><code class='java'> TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT);1415 * TolkienCharacter pippin = new TolkienCharacter("Pippin", 28, HOBBIT);1416 * frodo.setFriend(pippin);1417 * pippin.setFriend(frodo);1418 *1419 * TolkienCharacter frodoClone = new TolkienCharacter("Frodo", 33, HOBBIT);1420 * TolkienCharacter pippinClone = new TolkienCharacter("Pippin", 28, HOBBIT);1421 * frodoClone.setFriend(pippinClone);1422 * pippinClone.setFriend(frodoClone);1423 *1424 * List&lt;TolkienCharacter&gt; hobbits = Arrays.asList(frodo, pippin);1425 *1426 * // fails if equals has not been overridden in TolkienCharacter as it would compares object references1427 * assertThat(hobbits).contains(frodoClone, pippinClone);1428 *1429 * // frodo/frodoClone and pippin/pippinClone are equals when doing a recursive property/field by property/field comparison1430 * assertThat(hobbits).usingRecursiveFieldByFieldElementComparator()1431 * .contains(frodoClone, pippinClone);</code>1432 * </pre>1433 *1434 * @return {@code this} assertion object.1435 * @since 2.5.0 / 3.5.01436 */1437 @CheckReturnValue1438 public SELF usingRecursiveFieldByFieldElementComparator() {1439 return usingExtendedByTypesElementComparator(new RecursiveFieldByFieldComparator(comparatorsForElementPropertyOrFieldNames,1440 comparatorsForElementPropertyOrFieldTypes));1441 }1442 /**1443 * Use field/property by field/property comparison on the <b>given fields/properties only</b> (including inherited1444 * fields/properties) instead of relying on actual type A <code>equals</code> method to compare group elements for1445 * incoming assertion checks. Private fields are included but this can be disabled using1446 * {@link Assertions#setAllowExtractingPrivateFields(boolean)}.1447 * <p>1448 * This can be handy if <code>equals</code> method of the objects to compare does not suit you.1449 * <p>1450 * You can specify a custom comparator per name or type of element field with1451 * {@link #usingComparatorForElementFieldsWithNames(Comparator, String...)}1452 * and {@link #usingComparatorForElementFieldsWithType(Comparator, Class)}.1453 * <p>1454 * Note that the comparison is <b>not</b> recursive, if one of the fields/properties is an Object, it will be compared1455 * to the other field/property using its <code>equals</code> method.1456 * </p>1457 * Example:1458 * <pre><code class='java'> TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT);1459 * TolkienCharacter sam = new TolkienCharacter("Sam", 38, HOBBIT);1460 *1461 * // frodo and sam both are hobbits, so they are equals when comparing only race1462 * assertThat(newArrayList(frodo)).usingElementComparatorOnFields("race").contains(sam); // OK1463 *1464 * // ... but not when comparing both name and race1465 * assertThat(newArrayList(frodo)).usingElementComparatorOnFields("name", "race").contains(sam); // FAIL</code></pre>1466 *1467 * @param fields the fields/properties to compare using element comparators1468 * @return {@code this} assertion object.1469 */1470 @CheckReturnValue1471 public SELF usingElementComparatorOnFields(String... fields) {1472 return usingExtendedByTypesElementComparator(new OnFieldsComparator(comparatorsForElementPropertyOrFieldNames,1473 comparatorsForElementPropertyOrFieldTypes,1474 fields));1475 }1476 protected SELF usingComparisonStrategy(ComparisonStrategy comparisonStrategy) {1477 iterables = new Iterables(comparisonStrategy);1478 return myself;1479 }1480 /**1481 * Use field/property by field/property comparison on all fields/properties <b>except</b> the given ones (including inherited1482 * fields/properties) instead of relying on actual type A <code>equals</code> method to compare group elements for1483 * incoming assertion checks. Private fields are included but this can be disabled using1484 * {@link Assertions#setAllowExtractingPrivateFields(boolean)}.1485 * <p>1486 * This can be handy if <code>equals</code> method of the objects to compare does not suit you.1487 * <p>1488 * You can specify a custom comparator per name or type of element field with1489 * {@link #usingComparatorForElementFieldsWithNames(Comparator, String...)}1490 * and {@link #usingComparatorForElementFieldsWithType(Comparator, Class)}.1491 * <p>1492 * Note that the comparison is <b>not</b> recursive, if one of the fields/properties is an Object, it will be compared1493 * to the other field/property using its <code>equals</code> method.1494 * </p>1495 * Example:1496 * <pre><code class='java'> TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT);1497 * TolkienCharacter sam = new TolkienCharacter("Sam", 38, HOBBIT);1498 *1499 * // frodo and sam both are hobbits, so they are equals when comparing only race (i.e. ignoring all other fields)1500 * assertThat(newArrayList(frodo)).usingElementComparatorIgnoringFields("name", "age").contains(sam); // OK1501 *1502 * // ... but not when comparing both name and race1503 * assertThat(newArrayList(frodo)).usingElementComparatorIgnoringFields("age").contains(sam); // FAIL</code></pre>1504 *1505 * @return {@code this} assertion object.1506 */1507 @CheckReturnValue1508 public SELF usingElementComparatorIgnoringFields(String... fields) {1509 return usingExtendedByTypesElementComparator(new IgnoringFieldsComparator(comparatorsForElementPropertyOrFieldNames,1510 comparatorsForElementPropertyOrFieldTypes,1511 fields));1512 }1513 /**1514 * Enable hexadecimal representation of Iterable elements instead of standard representation in error messages.1515 * <p>1516 * It can be useful to better understand what the error was with a more meaningful error message.1517 * <p>1518 * Example1519 * <pre><code class='java'> final List&lt;Byte&gt; bytes = newArrayList((byte) 0x10, (byte) 0x20);</code></pre>1520 *1521 * With standard error message:1522 * <pre><code class='java'> assertThat(bytes).contains((byte) 0x30);1523 *1524 * Expecting:1525 * &lt;[16, 32]&gt;1526 * to contain:1527 * &lt;[48]&gt;1528 * but could not find:1529 * &lt;[48]&gt;</code></pre>1530 *1531 * With Hexadecimal error message:1532 * <pre><code class='java'> assertThat(bytes).inHexadecimal().contains((byte) 0x30);1533 *1534 * Expecting:1535 * &lt;[0x10, 0x20]&gt;1536 * to contain:1537 * &lt;[0x30]&gt;1538 * but could not find:1539 * &lt;[0x30]&gt;</code></pre>1540 *1541 * @return {@code this} assertion object.1542 */1543 @Override1544 @CheckReturnValue1545 public SELF inHexadecimal() {1546 return super.inHexadecimal();1547 }1548 /**1549 * Enable binary representation of Iterable elements instead of standard representation in error messages.1550 * <p>1551 * Example:1552 * <pre><code class='java'> final List&lt;Byte&gt; bytes = newArrayList((byte) 0x10, (byte) 0x20);</code></pre>1553 *1554 * With standard error message:1555 * <pre><code class='java'> assertThat(bytes).contains((byte) 0x30);1556 *1557 * Expecting:1558 * &lt;[16, 32]&gt;1559 * to contain:1560 * &lt;[48]&gt;1561 * but could not find:1562 * &lt;[48]&gt;</code></pre>1563 *1564 * With binary error message:1565 * <pre><code class='java'> assertThat(bytes).inBinary().contains((byte) 0x30);1566 *1567 * Expecting:1568 * &lt;[0b00010000, 0b00100000]&gt;1569 * to contain:1570 * &lt;[0b00110000]&gt;1571 * but could not find:1572 * &lt;[0b00110000]&gt;</code></pre>1573 *1574 * @return {@code this} assertion object.1575 */1576 @Override1577 @CheckReturnValue1578 public SELF inBinary() {1579 return super.inBinary();1580 }1581 /**1582 * Filter the iterable under test keeping only elements having a property or field equal to {@code expectedValue}, the1583 * property/field is specified by {@code propertyOrFieldName} parameter.1584 * <p>1585 * The filter first tries to get the value from a property (named {@code propertyOrFieldName}), if no such property1586 * exists it tries to read the value from a field. Reading private fields is supported by default, this can be1587 * globally disabled by calling {@link Assertions#setAllowExtractingPrivateFields(boolean)1588 * Assertions.setAllowExtractingPrivateFields(false)}.1589 * <p>1590 * When reading <b>nested</b> property/field, if an intermediate value is null the whole nested property/field is1591 * considered to be null, thus reading "address.street.name" value will return null if "street" value is null.1592 * <p>1593 *1594 * As an example, let's check all employees 800 years old (yes, special employees):1595 * <pre><code class='java'> Employee yoda = new Employee(1L, new Name("Yoda"), 800);1596 * Employee obiwan = new Employee(2L, new Name("Obiwan"), 800);1597 * Employee luke = new Employee(3L, new Name("Luke", "Skywalker"), 26);1598 * Employee noname = new Employee(4L, null, 50);1599 *1600 * List&lt;Employee&gt; employees = newArrayList(yoda, luke, obiwan, noname);1601 *1602 * assertThat(employees).filteredOn("age", 800)1603 * .containsOnly(yoda, obiwan);</code></pre>1604 *1605 * Nested properties/fields are supported:1606 * <pre><code class='java'> // Name is bean class with 'first' and 'last' String properties1607 *1608 * // name is null for noname =&gt; it does not match the filter on "name.first"1609 * assertThat(employees).filteredOn("name.first", "Luke")1610 * .containsOnly(luke);1611 *1612 * assertThat(employees).filteredOn("name.last", "Vader")1613 * .isEmpty();</code></pre>1614 * <p>1615 * If you want to filter on null value, use {@link #filteredOnNull(String)} as Java will resolve the call to1616 * {@link #filteredOn(String, FilterOperator)} instead of this method.1617 * <p>1618 * An {@link IntrospectionError} is thrown if the given propertyOrFieldName can't be found in one of the iterable1619 * elements.1620 * <p>1621 * You can chain filters:1622 * <pre><code class='java'> // fellowshipOfTheRing is a list of TolkienCharacter having race and name fields1623 * // 'not' filter is statically imported from Assertions.not1624 *1625 * assertThat(fellowshipOfTheRing).filteredOn("race.name", "Man")1626 * .filteredOn("name", not("Boromir"))1627 * .containsOnly(aragorn);</code></pre>1628 *1629 * If you need more complex filter, use {@link #filteredOn(Condition)} and provide a {@link Condition} to specify the1630 * filter to apply.1631 *1632 * @param propertyOrFieldName the name of the property or field to read1633 * @param expectedValue the value to compare element's property or field with1634 * @return a new assertion object with the filtered iterable under test1635 * @throws IllegalArgumentException if the given propertyOrFieldName is {@code null} or empty.1636 * @throws IntrospectionError if the given propertyOrFieldName can't be found in one of the iterable elements.1637 */1638 @CheckReturnValue1639 public AbstractListAssert<?, List<? extends ELEMENT>, ELEMENT, ObjectAssert<ELEMENT>> filteredOn(String propertyOrFieldName,1640 Object expectedValue) {1641 Filters<? extends ELEMENT> filter = filter((Iterable<? extends ELEMENT>) actual);1642 Iterable<? extends ELEMENT> filteredIterable = filter.with(propertyOrFieldName, expectedValue).get();1643 return newListAssertInstance(newArrayList(filteredIterable));1644 }1645 /**1646 * Filter the iterable under test keeping only elements whose property or field specified by1647 * {@code propertyOrFieldName} is null.1648 * <p>1649 * The filter first tries to get the value from a property (named {@code propertyOrFieldName}), if no such property1650 * exists it tries to read the value from a field. Reading private fields is supported by default, this can be1651 * globally disabled by calling {@link Assertions#setAllowExtractingPrivateFields(boolean)1652 * Assertions.setAllowExtractingPrivateFields(false)}.1653 * <p>1654 * When reading <b>nested</b> property/field, if an intermediate value is null the whole nested property/field is1655 * considered to be null, thus reading "address.street.name" value will return null if "street" value is null.1656 * <p>1657 * As an example, let's check all employees 800 years old (yes, special employees):1658 * <pre><code class='java'> Employee yoda = new Employee(1L, new Name("Yoda"), 800);1659 * Employee obiwan = new Employee(2L, new Name("Obiwan"), 800);1660 * Employee luke = new Employee(3L, new Name("Luke", "Skywalker"), 26);1661 * Employee noname = new Employee(4L, null, 50);1662 *1663 * List&lt;Employee&gt; employees = newArrayList(yoda, luke, obiwan, noname);1664 *1665 * assertThat(employees).filteredOnNull("name")1666 * .containsOnly(noname);</code></pre>1667 *1668 * Nested properties/fields are supported:1669 * <pre><code class='java'> // Name is bean class with 'first' and 'last' String properties1670 *1671 * assertThat(employees).filteredOnNull("name.last")1672 * .containsOnly(yoda, obiwan, noname);</code></pre>1673 *1674 * An {@link IntrospectionError} is thrown if the given propertyOrFieldName can't be found in one of the iterable1675 * elements.1676 * <p>1677 * If you need more complex filter, use {@link #filteredOn(Condition)} and provide a {@link Condition} to specify the1678 * filter to apply.1679 *1680 * @param propertyOrFieldName the name of the property or field to read1681 * @return a new assertion object with the filtered iterable under test1682 * @throws IntrospectionError if the given propertyOrFieldName can't be found in one of the iterable elements.1683 */1684 @CheckReturnValue1685 public AbstractListAssert<?, List<? extends ELEMENT>, ELEMENT, ObjectAssert<ELEMENT>> filteredOnNull(String propertyOrFieldName) {1686 // need to cast nulll to Object otherwise it calls :1687 // filteredOn(String propertyOrFieldName, FilterOperation<?> filterOperation)1688 return filteredOn(propertyOrFieldName, (Object) null);1689 }1690 /**1691 * Filter the iterable under test keeping only elements having a property or field matching the filter expressed with1692 * the {@link FilterOperator}, the property/field is specified by {@code propertyOrFieldName} parameter.1693 * <p>1694 * The existing filters are :1695 * <ul>1696 * <li> {@link Assertions#not(Object) not(Object)}</li>1697 * <li> {@link Assertions#in(Object...) in(Object...)}</li>1698 * <li> {@link Assertions#notIn(Object...) notIn(Object...)}</li>1699 * </ul>1700 * <p>1701 * Whatever filter is applied, it first tries to get the value from a property (named {@code propertyOrFieldName}), if1702 * no such property exists it tries to read the value from a field. Reading private fields is supported by default,1703 * this can be globally disabled by calling {@link Assertions#setAllowExtractingPrivateFields(boolean)1704 * Assertions.setAllowExtractingPrivateFields(false)}.1705 * <p>1706 * When reading <b>nested</b> property/field, if an intermediate value is null the whole nested property/field is1707 * considered to be null, thus reading "address.street.name" value will return null if "street" value is null.1708 * <p>1709 *1710 * As an example, let's check stuff on some special employees :1711 * <pre><code class='java'> Employee yoda = new Employee(1L, new Name("Yoda"), 800);1712 * Employee obiwan = new Employee(2L, new Name("Obiwan"), 800);1713 * Employee luke = new Employee(3L, new Name("Luke", "Skywalker"), 26);1714 *1715 * List&lt;Employee&gt; employees = newArrayList(yoda, luke, obiwan, noname);1716 *1717 * // 'not' filter is statically imported from Assertions.not1718 * assertThat(employees).filteredOn("age", not(800))1719 * .containsOnly(luke);1720 *1721 * // 'in' filter is statically imported from Assertions.in1722 * // Name is bean class with 'first' and 'last' String properties1723 * assertThat(employees).filteredOn("name.first", in("Yoda", "Luke"))1724 * .containsOnly(yoda, luke);1725 *1726 * // 'notIn' filter is statically imported from Assertions.notIn1727 * assertThat(employees).filteredOn("name.first", notIn("Yoda", "Luke"))1728 * .containsOnly(obiwan);</code></pre>1729 *1730 * An {@link IntrospectionError} is thrown if the given propertyOrFieldName can't be found in one of the iterable1731 * elements.1732 * <p>1733 * Note that combining filter operators is not supported, thus the following code is not correct:1734 * <pre><code class='java'> // Combining filter operators like not(in(800)) is NOT supported1735 * // -&gt; throws UnsupportedOperationException1736 * assertThat(employees).filteredOn("age", not(in(800)))1737 * .contains(luke);</code></pre>1738 * <p>1739 * You can chain filters:1740 * <pre><code class='java'> // fellowshipOfTheRing is a list of TolkienCharacter having race and name fields1741 * // 'not' filter is statically imported from Assertions.not1742 *1743 * assertThat(fellowshipOfTheRing).filteredOn("race.name", "Man")1744 * .filteredOn("name", not("Boromir"))1745 * .containsOnly(aragorn);</code></pre>1746 *1747 * If you need more complex filter, use {@link #filteredOn(Condition)} and provide a {@link Condition} to specify the1748 * filter to apply.1749 *1750 * @param propertyOrFieldName the name of the property or field to read1751 * @param filterOperator the filter operator to apply1752 * @return a new assertion object with the filtered iterable under test1753 * @throws IllegalArgumentException if the given propertyOrFieldName is {@code null} or empty.1754 */1755 @CheckReturnValue1756 public AbstractListAssert<?, List<? extends ELEMENT>, ELEMENT, ObjectAssert<ELEMENT>> filteredOn(String propertyOrFieldName,1757 FilterOperator<?> filterOperator) {1758 checkNotNull(filterOperator);1759 Filters<? extends ELEMENT> filter = filter((Iterable<? extends ELEMENT>) actual).with(propertyOrFieldName);1760 filterOperator.applyOn(filter);1761 return newListAssertInstance(newArrayList(filter.get()));1762 }1763 /**1764 * Filter the iterable under test keeping only elements matching the given {@link Condition}.1765 * <p>1766 * Example : check old employees whose age &gt; 100:1767 * <pre><code class='java'> Employee yoda = new Employee(1L, new Name("Yoda"), 800);1768 * Employee obiwan = new Employee(2L, new Name("Obiwan"), 800);1769 * Employee luke = new Employee(3L, new Name("Luke", "Skywalker"), 26);1770 * Employee noname = new Employee(4L, null, 50);1771 *1772 * List&lt;Employee&gt; employees = newArrayList(yoda, luke, obiwan, noname);1773 *1774 * // old employee condition, "old employees" describes the condition in error message1775 * // you just have to implement 'matches' method1776 * Condition&lt;Employee&gt; oldEmployees = new Condition&lt;Employee&gt;("old employees") {1777 * {@literal @}Override1778 * public boolean matches(Employee employee) {1779 * return employee.getAge() &gt; 100;1780 * }1781 * };1782 * }1783 * assertThat(employees).filteredOn(oldEmployees)1784 * .containsOnly(yoda, obiwan);</code></pre>1785 *1786 * You can combine {@link Condition} with condition operator like {@link Not}:1787 * <pre><code class='java'> // 'not' filter is statically imported from Assertions.not1788 * assertThat(employees).filteredOn(not(oldEmployees))1789 * .contains(luke, noname);</code></pre>1790 *1791 * @param condition the filter condition / predicate1792 * @return a new assertion object with the filtered iterable under test1793 * @throws IllegalArgumentException if the given condition is {@code null}.1794 */1795 @CheckReturnValue1796 public AbstractListAssert<?, List<? extends ELEMENT>, ELEMENT, ObjectAssert<ELEMENT>> filteredOn(Condition<? super ELEMENT> condition) {1797 Filters<? extends ELEMENT> filter = filter((Iterable<? extends ELEMENT>) actual);1798 Iterable<? extends ELEMENT> filteredIterable = filter.being(condition).get();1799 return newListAssertInstance(newArrayList(filteredIterable));1800 }1801 // navigable assertions1802 /**1803 * Navigate and allow to perform assertions on the first element of the {@link Iterable} under test.1804 * <p>1805 * By default available assertions after {@code first()} are {@code Object} assertions, it is possible though to1806 * get more specific assertions if you create {@code IterableAssert} with either:1807 * <ul>1808 * <li>the element assert class, see: {@link Assertions#assertThat(Iterable, Class) assertThat(Iterable, element assert class)}</li>1809 * <li>an assert factory used that knows how to create elements assertion, see: {@link Assertions#assertThat(Iterable, AssertFactory) assertThat(Iterable, element assert factory)}</li>1810 * </ul>1811 * <p>1812 * Example: default {@code Object} assertions1813 * <pre><code class='java'> // default iterable assert =&gt; element assert is ObjectAssert1814 * Iterable&lt;TolkienCharacter&gt; hobbits = newArrayList(frodo, sam, pippin);1815 *1816 * // assertion succeeds, only Object assertions are available after first()1817 * assertThat(hobbits).first()1818 * .isEqualTo(frodo);1819 *1820 * // assertion fails1821 * assertThat(hobbits).first()1822 * .isEqualTo(pippin);</code></pre>1823 * <p>1824 * If you have created the Iterable assertion using an {@link AssertFactory} or the element assert class,1825 * you will be able to chain {@code first()} with more specific typed assertion.1826 * <p>1827 * Example: use of {@code String} assertions after {@code first()}1828 * <pre><code class='java'> Iterable&lt;String&gt; hobbits = newArrayList("frodo", "sam", "pippin");1829 *1830 * // assertion succeeds1831 * // String assertions are available after first()1832 * assertThat(hobbits, StringAssert.class).first()1833 * .startsWith("fro")1834 * .endsWith("do");1835 * // assertion fails1836 * assertThat(hobbits, StringAssert.class).first()1837 * .startsWith("pip");</code></pre>1838 *1839 * @return the assertion on the first element1840 * @throws AssertionError if the actual {@link Iterable} is empty.1841 * @since 2.5.0 / 3.5.01842 */1843 @CheckReturnValue1844 public ELEMENT_ASSERT first() {1845 isNotEmpty();1846 return toAssert(actual.iterator().next(), navigationDescription("check first element")); // TOD better description1847 }1848 /**1849 * Navigate and allow to perform assertions on the first element of the {@link Iterable} under test.1850 * <p>1851 * By default available assertions after {@code last()} are {@code Object} assertions, it is possible though to1852 * get more specific assertions if you create {@code IterableAssert} with either:1853 * <ul>1854 * <li>the element assert class, see: {@link Assertions#assertThat(Iterable, Class) assertThat(Iterable, element assert class)}</li>1855 * <li>an assert factory used that knows how to create elements assertion, see: {@link Assertions#assertThat(Iterable, AssertFactory) assertThat(Iterable, element assert factory)}</li>1856 * </ul>1857 * <p>1858 * Example: default {@code Object} assertions1859 * <pre><code class='java'> // default iterable assert =&gt; element assert is ObjectAssert1860 * Iterable&lt;TolkienCharacter&gt; hobbits = newArrayList(frodo, sam, pippin);1861 *1862 * // assertion succeeds, only Object assertions are available after last()1863 * assertThat(hobbits).last()1864 * .isEqualTo(pippin);1865 *1866 * // assertion fails1867 * assertThat(hobbits).last()1868 * .isEqualTo(frodo);</code></pre>1869 * <p>1870 * If you have created the Iterable assertion using an {@link AssertFactory} or the element assert class,1871 * you will be able to chain {@code last()} with more specific typed assertion.1872 * <p>1873 * Example: use of {@code String} assertions after {@code last()}1874 * <pre><code class='java'> Iterable&lt;String&gt; hobbits = newArrayList("frodo", "sam", "pippin");1875 *1876 * // assertion succeeds1877 * // String assertions are available after last()1878 * assertThat(hobbits, StringAssert.class).last()1879 * .startsWith("pi")1880 * .endsWith("in");1881 * // assertion fails1882 * assertThat(hobbits, StringAssert.class).last()1883 * .startsWith("fro");</code></pre>1884 *1885 * @return the assertion on the first element1886 * @throws AssertionError if the actual {@link Iterable} is empty.1887 * @since 2.5.0 / 3.5.01888 */1889 @CheckReturnValue1890 public ELEMENT_ASSERT last() {1891 isNotEmpty();1892 return toAssert(lastElement(), navigationDescription("check last element"));1893 }1894 private ELEMENT lastElement() {1895 if (actual instanceof List) {1896 List<? extends ELEMENT> list = (List<? extends ELEMENT>) actual;1897 return list.get(list.size() - 1);1898 }1899 Iterator<? extends ELEMENT> actualIterator = actual.iterator();1900 ELEMENT last = actualIterator.next();1901 while (actualIterator.hasNext()) {1902 last = actualIterator.next();1903 }1904 return last;1905 }1906 /**1907 * Navigate and allow to perform assertions on the chosen element of the {@link Iterable} under test.1908 * <p>1909 * By default available assertions after {@code element(index)} are {@code Object} assertions, it is possible though to1910 * get more specific assertions if you create {@code IterableAssert} with either:1911 * <ul>1912 * <li>the element assert class, see: {@link Assertions#assertThat(Iterable, Class) assertThat(Iterable, element assert class)}</li>1913 * <li>an assert factory used that knows how to create elements assertion, see: {@link Assertions#assertThat(Iterable, AssertFactory) assertThat(Iterable, element assert factory)}</li>1914 * </ul>1915 * <p>1916 * Example: default {@code Object} assertions1917 * <pre><code class='java'> // default iterable assert =&gt; element assert is ObjectAssert1918 * Iterable&lt;TolkienCharacter&gt; hobbits = newArrayList(frodo, sam, pippin);1919 *1920 * // assertion succeeds, only Object assertions are available after element(index)1921 * assertThat(hobbits).element(1)1922 * .isEqualTo(sam);1923 *1924 * // assertion fails1925 * assertThat(hobbits).element(1)1926 * .isEqualTo(pippin);</code></pre>1927 * <p>1928 * If you have created the Iterable assertion using an {@link AssertFactory} or the element assert class,1929 * you will be able to chain {@code element(index)} with more specific typed assertion.1930 * <p>1931 * Example: use of {@code String} assertions after {@code element(index)}1932 * <pre><code class='java'> Iterable&lt;String&gt; hobbits = newArrayList("frodo", "sam", "pippin");1933 *1934 * // assertion succeeds1935 * // String assertions are available after element(index)1936 * assertThat(hobbits, StringAssert.class).element(1)1937 * .startsWith("sa")1938 * .endsWith("am");1939 * // assertion fails1940 * assertThat(hobbits, StringAssert.class).element(1)1941 * .startsWith("fro");</code></pre>1942 *1943 * @return the assertion on the given element1944 * @throws AssertionError if the given index is out of bound.1945 * @since 2.5.0 / 3.5.01946 */1947 @CheckReturnValue1948 public ELEMENT_ASSERT element(int index) {1949 isNotEmpty();1950 assertThat(index).describedAs(navigationDescription("check index validity"))1951 .isBetween(0, IterableUtil.sizeOf(actual) - 1);1952 ELEMENT elementAtIndex = null;1953 if (actual instanceof List) {1954 List<? extends ELEMENT> list = (List<? extends ELEMENT>) actual;1955 elementAtIndex = list.get(index);1956 } else {1957 Iterator<? extends ELEMENT> actualIterator = actual.iterator();1958 for (int i = 0; i < index; i++) {1959 actualIterator.next();1960 }1961 elementAtIndex = actualIterator.next();1962 }1963 return toAssert(elementAtIndex, navigationDescription("element at index " + index));1964 }1965 protected abstract ELEMENT_ASSERT toAssert(ELEMENT value, String description);1966 protected String navigationDescription(String propertyName) {1967 String text = descriptionText();1968 if (Strings.isNullOrEmpty(text)) {1969 text = removeAssert(this.getClass().getSimpleName());1970 }1971 return text + " " + propertyName;1972 }1973 private static String removeAssert(String text) {1974 return text.endsWith(ASSERT) ? text.substring(0, text.length() - ASSERT.length()) : text;1975 }1976 // override methods to avoid compilation error when chaining an AbstractAssert method with a AbstractIterableAssert1977 // one on raw types.1978 @Override1979 @CheckReturnValue1980 public SELF as(String description, Object... args) {1981 return super.as(description, args);1982 }1983 @Override1984 @CheckReturnValue1985 public SELF as(Description description) {1986 return super.as(description);1987 }1988 @Override1989 @CheckReturnValue1990 public SELF describedAs(Description description) {1991 return super.describedAs(description);1992 }1993 @Override1994 @CheckReturnValue1995 public SELF describedAs(String description, Object... args) {1996 return super.describedAs(description, args);1997 }1998 @Override1999 public SELF doesNotHave(Condition<? super ACTUAL> condition) {2000 return super.doesNotHave(condition);2001 }2002 @Override2003 public SELF doesNotHaveSameClassAs(Object other) {2004 return super.doesNotHaveSameClassAs(other);2005 }2006 @Override2007 public SELF has(Condition<? super ACTUAL> condition) {2008 return super.has(condition);2009 }2010 @Override2011 public SELF hasSameClassAs(Object other) {2012 return super.hasSameClassAs(other);2013 }2014 @Override2015 public SELF hasToString(String expectedToString) {2016 return super.hasToString(expectedToString);2017 }2018 @Override2019 public SELF is(Condition<? super ACTUAL> condition) {2020 return super.is(condition);2021 }2022 @Override2023 public SELF isEqualTo(Object expected) {2024 return super.isEqualTo(expected);2025 }2026 @Override2027 public SELF isExactlyInstanceOf(Class<?> type) {2028 return super.isExactlyInstanceOf(type);2029 }2030 @Override2031 public SELF isIn(Iterable<?> values) {2032 return super.isIn(values);2033 }2034 @Override2035 public SELF isIn(Object... values) {2036 return super.isIn(values);2037 }2038 @Override2039 public SELF isInstanceOf(Class<?> type) {2040 return super.isInstanceOf(type);2041 }2042 @Override2043 public SELF isInstanceOfAny(Class<?>... types) {2044 return super.isInstanceOfAny(types);2045 }2046 @Override2047 public SELF isNot(Condition<? super ACTUAL> condition) {2048 return super.isNot(condition);2049 }2050 @Override2051 public SELF isNotEqualTo(Object other) {2052 return super.isNotEqualTo(other);2053 }2054 @Override2055 public SELF isNotExactlyInstanceOf(Class<?> type) {2056 return super.isNotExactlyInstanceOf(type);2057 }2058 @Override2059 public SELF isNotIn(Iterable<?> values) {2060 return super.isNotIn(values);2061 }2062 @Override2063 public SELF isNotIn(Object... values) {2064 return super.isNotIn(values);2065 }2066 @Override2067 public SELF isNotInstanceOf(Class<?> type) {2068 return super.isNotInstanceOf(type);2069 }2070 @Override2071 public SELF isNotInstanceOfAny(Class<?>... types) {2072 return super.isNotInstanceOfAny(types);2073 }2074 @Override2075 public SELF isNotOfAnyClassIn(Class<?>... types) {2076 return super.isNotOfAnyClassIn(types);2077 }2078 @Override2079 public SELF isNotNull() {2080 return super.isNotNull();2081 }2082 @Override2083 public SELF isNotSameAs(Object other) {2084 return super.isNotSameAs(other);2085 }2086 @Override2087 public SELF isOfAnyClassIn(Class<?>... types) {2088 return super.isOfAnyClassIn(types);2089 }2090 @Override2091 public SELF isSameAs(Object expected) {2092 return super.isSameAs(expected);2093 }2094 @Override2095 @CheckReturnValue2096 public SELF overridingErrorMessage(String newErrorMessage, Object... args) {2097 return super.overridingErrorMessage(newErrorMessage, args);2098 }2099 @Override2100 @CheckReturnValue2101 public SELF usingDefaultComparator() {2102 return super.usingDefaultComparator();2103 }2104 @Override2105 @CheckReturnValue2106 public SELF usingComparator(Comparator<? super ACTUAL> customComparator) {2107 return super.usingComparator(customComparator);2108 }2109 @Override2110 @CheckReturnValue2111 public SELF withFailMessage(String newErrorMessage, Object... args) {2112 return super.withFailMessage(newErrorMessage, args);2113 }2114 @Override2115 @CheckReturnValue2116 public SELF withThreadDumpOnError() {2117 return super.withThreadDumpOnError();2118 }2119 /**2120 * Returns an {@code Assert} object that allows performing assertions on the size of the {@link Iterable} under test.2121 * <p>2122 * Once this method is called, the object under test is no longer the {@link Iterable} but its size,2123 * to perform assertions on the {@link Iterable}, call {@link AbstractIterableSizeAssert#returnToIterable()}.2124 * <p>2125 * Example:2126 * <pre><code class='java'> Iterable&lt;Ring&gt; elvesRings = newArrayList(vilya, nenya, narya);2127 *2128 * // assertion will pass:2129 * assertThat(elvesRings).size().isGreaterThan(1)2130 * .isLessThanOrEqualTo(3)2131 * .returnToIterable().contains(narya)2132 * .doesNotContain(oneRing);2133 *2134 * // assertion will fail:2135 * assertThat(elvesRings).size().isGreaterThan(3);</code></pre>2136 *2137 * @return AbstractIterableSizeAssert built with the {@code Iterable}'s size.2138 * @throws NullPointerException if the given {@code Iterable} is {@code null}.2139 */2140 @SuppressWarnings({ "rawtypes", "unchecked" })2141 @CheckReturnValue2142 public AbstractIterableSizeAssert<SELF, ACTUAL, ELEMENT, ELEMENT_ASSERT> size() {2143 Preconditions.checkNotNull(actual, "Can not perform assertions on the size of a null iterable.");2144 return new IterableSizeAssert(this, IterableUtil.sizeOf(actual));2145 }2146}...

Full Screen

Full Screen

Source:Maps.java Github

copy

Full Screen

...339 }340 private static <K> Set<K> getNotExpectedKeys(Map<K, ?> actual, K[] expectedKeys) {341 // Stream API avoided for performance reasons342 try {343 Map<K, ?> clonedMap = clone(actual);344 for (K expectedKey : expectedKeys) {345 clonedMap.remove(expectedKey);346 }347 return clonedMap.keySet();348 } catch (NoSuchMethodException | RuntimeException e) {349 // actual cannot be cloned or is unmodifiable, falling back to LinkedHashMap350 Map<K, ?> copiedMap = new LinkedHashMap<>(actual);351 for (K expectedKey : expectedKeys) {352 copiedMap.remove(expectedKey);353 }354 return copiedMap.keySet();355 }356 }357 @SuppressWarnings("unchecked")358 private static <K, V> Map<K, V> clone(Map<K, V> map) throws NoSuchMethodException {359 if (isMultiValueMapAdapterInstance(map)) throw new IllegalArgumentException("Cannot clone MultiValueMapAdapter");360 try {361 if (map instanceof Cloneable) {362 return (Map<K, V>) map.getClass().getMethod("clone").invoke(map);363 }364 try {365 // try with copying constructor366 return map.getClass().getConstructor(Map.class).newInstance(map);367 } catch (NoSuchMethodException e) {368 // try with default constructor369 Map<K, V> newMap = map.getClass().getConstructor().newInstance();370 newMap.putAll(map);371 return newMap;372 }373 } catch (IllegalAccessException | InvocationTargetException | InstantiationException e) {374 throw new IllegalStateException(e);375 }376 }377 private static boolean isMultiValueMapAdapterInstance(Map<?, ?> map) {378 return isInstanceOf(map, "org.springframework.util.MultiValueMapAdapter");379 }380 private static boolean isInstanceOf(Object object, String className) {381 try {382 Class<?> type = Class.forName(className);383 return type.isInstance(object);384 } catch (ClassNotFoundException e) {385 return false;386 }387 }388 public <K, V> void assertContainsValue(AssertionInfo info, Map<K, V> actual, V value) {389 assertNotNull(info, actual);390 if (!containsValue(actual, value)) throw failures.failure(info, shouldContainValue(actual, value));391 }392 public <K, V> void assertContainsValues(AssertionInfo info, Map<K, V> actual, V[] values) {393 assertNotNull(info, actual);394 requireNonNull(values, "The array of values to look for should not be null");395 if (actual.isEmpty() && values.length == 0) return;396 failIfEmpty(values, valuesToLookForIsEmpty());397 Set<V> notFound = getNotFoundValues(actual, values);398 if (!notFound.isEmpty()) throw failures.failure(info, shouldContainValues(actual, notFound));399 }400 public <K, V> void assertDoesNotContainValue(AssertionInfo info, Map<K, V> actual, V value) {401 assertNotNull(info, actual);402 if (containsValue(actual, value)) throw failures.failure(info, shouldNotContainValue(actual, value));403 }404 private static <V> Set<V> getNotFoundValues(Map<?, V> actual, V[] expectedValues) {405 // Stream API avoided for performance reasons406 Set<V> notFound = new LinkedHashSet<>();407 for (V expectedValue : expectedValues) {408 if (!containsValue(actual, expectedValue)) notFound.add(expectedValue);409 }410 return notFound;411 }412 private static <V> boolean containsValue(Map<?, V> actual, V value) {413 try {414 return actual.containsValue(value);415 } catch (NullPointerException e) {416 if (value == null) return false; // null values not permitted417 throw e;418 }419 }420 public <K, V> void assertContainsOnly(AssertionInfo info, Map<K, V> actual, Entry<? extends K, ? extends V>[] entries) {421 doCommonContainsCheck(info, actual, entries);422 if (actual.isEmpty() && entries.length == 0) return;423 failIfEntriesIsEmptySinceActualIsNotEmpty(info, actual, entries);424 Set<Entry<? extends K, ? extends V>> notFound = getNotFoundEntries(actual, entries);425 Set<Entry<K, V>> notExpected = getNotExpectedEntries(actual, entries);426 if (!(notFound.isEmpty() && notExpected.isEmpty()))427 throw failures.failure(info, shouldContainOnly(actual, entries, notFound, notExpected));428 }429 private static <K, V> Set<Entry<? extends K, ? extends V>> getNotFoundEntries(Map<K, V> actual,430 Entry<? extends K, ? extends V>[] entries) {431 // Stream API avoided for performance reasons432 Set<Entry<? extends K, ? extends V>> notFound = new LinkedHashSet<>();433 for (Entry<? extends K, ? extends V> entry : entries) {434 if (!containsEntry(actual, entry)) notFound.add(entry);435 }436 return notFound;437 }438 private static <K, V> Set<Entry<K, V>> getNotExpectedEntries(Map<K, V> actual, Entry<? extends K, ? extends V>[] entries) {439 // Stream API avoided for performance reasons440 Set<Entry<K, V>> notExpected = new LinkedHashSet<>();441 for (Entry<K, V> entry : mapWithoutExpectedEntries(actual, entries).entrySet()) {442 MapEntry<K, V> mapEntry = entry(entry.getKey(), entry.getValue());443 notExpected.add(mapEntry);444 }445 return notExpected;446 }447 private static <K, V> Map<K, V> mapWithoutExpectedEntries(Map<K, V> actual, Entry<? extends K, ? extends V>[] expectedEntries) {448 // Stream API avoided for performance reasons449 try {450 Map<K, V> clonedMap = clone(actual);451 removeEntries(clonedMap, expectedEntries);452 return clonedMap;453 } catch (NoSuchMethodException | RuntimeException e) {454 // actual cannot be cloned or is unmodifiable, falling back to LinkedHashMap455 Map<K, V> copiedMap = new LinkedHashMap<>(actual);456 removeEntries(copiedMap, expectedEntries);457 return copiedMap;458 }459 }460 private static <K, V> void removeEntries(Map<K, V> map, Entry<? extends K, ? extends V>[] entries) {461 for (Entry<? extends K, ? extends V> entry : entries) {462 // must perform deep equals comparison on values as Map.remove(Object, Object) relies on463 // Objects.equals which does not handle deep equality (e.g. arrays in map entry values)464 if (containsEntry(map, entry)) map.remove(entry.getKey());465 }466 }467 public <K, V> void assertContainsExactly(AssertionInfo info, Map<K, V> actual, Entry<? extends K, ? extends V>[] entries) {468 doCommonContainsCheck(info, actual, entries);...

Full Screen

Full Screen

clone

Using AI Code Generation

copy

Full Screen

1public class AssertJTest {2 public static void main(String[] args) {3 Map<String, String> map = new HashMap<>();4 map.put("key1", "value1");5 map.put("key2", "value2");6 Map<String, String> clonedMap = Maps.clone(map);7 System.out.println(clonedMap);8 }9}10{key1=value1, key2=value2}

Full Screen

Full Screen

clone

Using AI Code Generation

copy

Full Screen

1import org.assertj.core.internal.Maps;2import java.util.HashMap;3import java.util.Map;4public class Test {5 public static void main(String[] args) {6 Map<Integer, String> map = new HashMap<>();7 map.put(1, "one");8 map.put(2, "two");9 map.put(3, "three");10 map.put(4, "four");11 map.put(5, "five");12 Maps maps = new Maps();13 Map<Integer, String> clonedMap = maps.clone(map);14 System.out.println(clonedMap);15 }16}17{1=one, 2=two, 3=three, 4=four, 5=five}

Full Screen

Full Screen

clone

Using AI Code Generation

copy

Full Screen

1import org.assertj.core.util.Maps;2import java.util.Map;3import java.util.HashMap;4public class CloneMap {5 public static void main(String[] args) {6 Map<String, String> map = new HashMap<>();7 map.put("1", "one");8 map.put("2", "two");9 map.put("3", "three");10 System.out.println("Original Map: " + map);11 Map<String, String> clonedMap = Maps.clone(map);12 System.out.println("Cloned Map: " + clonedMap);13 }14}15Original Map: {1=one, 2=two, 3=t

Full Screen

Full Screen

clone

Using AI Code Generation

copy

Full Screen

1public class Maps_clone {2 public static void main(String[] args) {3 Maps maps = new Maps();4 HashMap<String, Integer> hashMap = new HashMap<String, Integer>();5 hashMap.put("A", 1);6 hashMap.put("B", 2);7 hashMap.put("C", 3);8 System.out.println("Map: " + hashMap);9 HashMap<String, Integer> cloneMap = maps.clone(hashMap);10 System.out.println("Cloned Map: " + cloneMap);11 }12}13Map: {A=1, B=2, C=3}14Cloned Map: {A=1, B=2, C=3}15Recommended Posts: AssertJ | Using isEmpty() method16AssertJ | Using isEmptyString() method17AssertJ | Using isNotEmptyString() method18AssertJ | Using isNotEmpty() method19AssertJ | Using isNotBlank() method20AssertJ | Using isNotInstanceOf() method21AssertJ | Using isNotSameAs() method22AssertJ | Using isNotSameClassAs() method23AssertJ | Using isNotSameSizeAs() method24AssertJ | Using isNotSameTimeAs() method25AssertJ | Using isNotSameYearAs() method26AssertJ | Using isNotSameMonthAs() method27AssertJ | Using isNotSameDayAs() method28AssertJ | Using isNotSameHourAs() method29AssertJ | Using isNotSameMinuteAs() method30AssertJ | Using isNotSameSecondAs() method31AssertJ | Using isNotSameMillisecondAs() method32AssertJ | Using isNotSameTimeZoneAs() method33AssertJ | Using isNotSameTimeAs() method34AssertJ | Using isNotSameYearAs() method35AssertJ | Using isNotSameMonthAs() method36AssertJ | Using isNotSameDayAs() method37AssertJ | Using isNotSameHourAs() method38AssertJ | Using isNotSameMinuteAs() method39AssertJ | Using isNotSameSecondAs() method40AssertJ | Using isNotSameMillisecondAs() method

Full Screen

Full Screen

clone

Using AI Code Generation

copy

Full Screen

1package com.puppycrawl.tools.checkstyle.checks.coding.missingclone;2import java.util.HashMap;3import java.util.Map;4public class InputMissingCloneCloneMethodOfAssertJMapsClass {5 public void testCloneMethodOfAssertJMapsClass() {6 Map<String, String> map = new HashMap<>();7 map.put("key", "value");8 Map<String, String> mapClone = Maps.instance().clone(map);9 }10}11[ERROR] /home/akmo/GSoC/NoClone/1.java:11:5: Missing a clone() method. [MissingClone]12package com.puppycrawl.tools.checkstyle.checks.coding.missingclone;13public class InputMissingCloneCloneMethodOfAssertJMapsClass {14 public void testCloneMethodOfAssertJMapsClass() {15 Map<String, String> map = new HashMap<>();16 map.put("key", "value");17 Map<String, String> mapClone = Maps.instance().clone(map);18 }19}20[ERROR] /home/akmo/GSoC/NoClone/1.java:10:5: Missing a clone() method. [MissingClone]

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.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful