Best Assertj code snippet using org.assertj.core.api.AbstractObjectArrayAssert.compare
Source:AbstractObjectArrayAssert.java
...351 return myself;352 }353 /**354 * Use field/property by field/property comparison (including inherited fields/properties) instead of relying on355 * actual type A <code>equals</code> method to compare group elements for incoming assertion checks. Private fields356 * are included but this can be disabled using {@link Assertions#setAllowExtractingPrivateFields(boolean)}.357 * <p/>358 * This can be handy if <code>equals</code> method of the objects to compare does not suit you.359 * <p/>360 * Note that the comparison is <b>not</b> recursive, if one of the fields/properties is an Object, it will be compared361 * to the other field/property using its <code>equals</code> method.362 * </p>363 * Example:364 * <pre><code class='java'> TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT);365 * TolkienCharacter frodoClone = new TolkienCharacter("Frodo", 33, HOBBIT);366 * 367 * // Fail if equals has not been overridden in TolkienCharacter as equals default implementation only compares references368 * assertThat(array(frodo)).contains(frodoClone);369 * 370 * // frodo and frodoClone are equals when doing a field by field comparison.371 * assertThat(array(frodo)).usingFieldByFieldElementComparator().contains(frodoClone);</code></pre>372 *373 * @return {@code this} assertion object.374 */375 public S usingFieldByFieldElementComparator() {376 return usingElementComparator(new FieldByFieldComparator());377 }378 /**379 * Use field/property by field/property comparison on the <b>given fields/properties only</b> (including inherited380 * fields/properties)instead of relying on actual type A <code>equals</code> method to compare group elements for381 * incoming assertion checks. Private fields are included but this can be disabled using382 * {@link Assertions#setAllowExtractingPrivateFields(boolean)}.383 * <p/>384 * This can be handy if <code>equals</code> method of the objects to compare does not suit you.385 * <p/>386 * Note that the comparison is <b>not</b> recursive, if one of the fields/properties is an Object, it will be compared387 * to the other field/property using its <code>equals</code> method.388 * </p>389 * Example:390 * <pre><code class='java'> TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT);391 * TolkienCharacter sam = new TolkienCharacter("Sam", 38, HOBBIT);392 * 393 * // frodo and sam both are hobbits, so they are equals when comparing only race394 * assertThat(array(frodo)).usingElementComparatorOnFields("race").contains(sam); // OK395 * 396 * // ... but not when comparing both name and race397 * assertThat(array(frodo)).usingElementComparatorOnFields("name", "race").contains(sam); // FAIL</code></pre>398 *399 * @return {@code this} assertion object.400 */401 public S usingElementComparatorOnFields(String... fields) {402 return usingElementComparator(new OnFieldsComparator(fields));403 }404 /**405 * Use field/property by field/property on all fields/properties <b>except</b> the given ones (including inherited406 * fields/properties)instead of relying on actual type A <code>equals</code> method to compare group elements for407 * incoming assertion checks. Private fields are included but this can be disabled using408 * {@link Assertions#setAllowExtractingPrivateFields(boolean)}.409 * <p/>410 * This can be handy if <code>equals</code> method of the objects to compare does not suit you.411 * <p/>412 * Note that the comparison is <b>not</b> recursive, if one of the fields/properties is an Object, it will be compared413 * to the other field/property using its <code>equals</code> method.414 * </p>415 * Example:416 * <pre><code class='java'> TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT);417 * TolkienCharacter sam = new TolkienCharacter("Sam", 38, HOBBIT);418 * 419 * // frodo and sam both are hobbits, so they are equals when comparing only race (i.e. ignoring all other fields)420 * assertThat(array(frodo)).usingElementComparatorIgnoringFields("name", "age").contains(sam); // OK421 * 422 * // ... but not when comparing both name and race423 * assertThat(array(frodo)).usingElementComparatorIgnoringFields("age").contains(sam); // FAIL</code></pre>424 *425 * @return {@code this} assertion object.426 */427 public S usingElementComparatorIgnoringFields(String... fields) {428 return usingElementComparator(new IgnoringFieldsComparator(fields));429 }430 /**431 * Extract the values of given field or property from the array's elements under test into a new array, this new array432 * becoming the array under test.433 * <p>434 * It allows you to test a field/property of the array's elements instead of testing the elements themselves, it can435 * be sometimes much less work !436 * <p>437 * Let's take an example to make things clearer :438 * <pre><code class='java'> // Build a array of TolkienCharacter, a TolkienCharacter has a name (String) and a Race (a class)439 * // they can be public field or properties, both works when extracting their values.440 * TolkienCharacter[] fellowshipOfTheRing = new TolkienCharacter[] {441 * new TolkienCharacter("Frodo", 33, HOBBIT),442 * new TolkienCharacter("Sam", 38, HOBBIT),443 * new TolkienCharacter("Gandalf", 2020, MAIA),444 * new TolkienCharacter("Legolas", 1000, ELF),445 * new TolkienCharacter("Pippin", 28, HOBBIT),446 * new TolkienCharacter("Gimli", 139, DWARF),447 * new TolkienCharacter("Aragorn", 87, MAN,448 * new TolkienCharacter("Boromir", 37, MAN)449 * };450 * 451 * // let's verify the names of TolkienCharacter in fellowshipOfTheRing :452 * 453 * assertThat(fellowshipOfTheRing).extracting("name")454 * .contains("Boromir", "Gandalf", "Frodo")455 * .doesNotContain("Sauron", "Elrond");456 * 457 * // you can also extract nested field/property like the name of Race :458 * 459 * assertThat(fellowshipOfTheRing).extracting("race.name")460 * .contains("Hobbit", "Elf")461 * .doesNotContain("Orc");</code></pre>462 * 463 * A property with the given name is looked for first, if it does not exist then a field with the given name464 * is looked for.465 * <p>466 * Note that the order of extracted field/property values is consistent with the array order.467 * 468 * @param fieldOrProperty the field/property to extract from the array under test469 * @return a new assertion object whose object under test is the array of extracted field/property values.470 * @throws IntrospectionError if no field or property exists with the given name471 */472 public ObjectArrayAssert<Object> extracting(String fieldOrProperty) {473 Object[] values = FieldsOrPropertiesExtractor.extract(actual, byName(fieldOrProperty));474 return new ObjectArrayAssert<>(values);475 }476 /**477 * Extract the values of given field or property from the array's elements under test into a new array, this new array478 * becoming the array under test with type.479 * <p>480 * It allows you to test a field/property of the array's elements instead of testing the elements themselves, it can481 * be sometimes much less work !482 * <p>483 * Let's take an example to make things clearer :484 * <pre><code class='java'> // Build an array of TolkienCharacter, a TolkienCharacter has a name (String) and a Race (a class)485 * // they can be public field or properties, both works when extracting their values.486 * TolkienCharacter[] fellowshipOfTheRing = new TolkienCharacter[] {487 * new TolkienCharacter("Frodo", 33, HOBBIT),488 * new TolkienCharacter("Sam", 38, HOBBIT),489 * new TolkienCharacter("Gandalf", 2020, MAIA),490 * new TolkienCharacter("Legolas", 1000, ELF),491 * new TolkienCharacter("Pippin", 28, HOBBIT),492 * new TolkienCharacter("Gimli", 139, DWARF),493 * new TolkienCharacter("Aragorn", 87, MAN,494 * new TolkienCharacter("Boromir", 37, MAN)495 * };496 * 497 * // let's verify the names of TolkienCharacter in fellowshipOfTheRing :498 * 499 * assertThat(fellowshipOfTheRing).extracting("name", String.class)500 * .contains("Boromir", "Gandalf", "Frodo")501 * .doesNotContain("Sauron", "Elrond");502 * 503 * // you can also extract nested field/property like the name of Race :504 * 505 * assertThat(fellowshipOfTheRing).extracting("race.name", String.class)506 * .contains("Hobbit", "Elf")507 * .doesNotContain("Orc");</code></pre>508 * 509 * A property with the given name is looked for first, if it does not exist then a field with the given name510 * is looked for.511 * <p>512 * Note that the order of extracted field/property values is consistent with the order of the array under test.513 * 514 * @param fieldOrProperty the field/property to extract from the array under test515 * @param extractingType type to return516 * @return a new assertion object whose object under test is the array of extracted field/property values.517 * @throws IntrospectionError if no field or property exists with the given name518 */519 public <P> ObjectArrayAssert<P> extracting(String fieldOrProperty, Class<P> extractingType) {520 @SuppressWarnings("unchecked")521 P[] values = (P[]) FieldsOrPropertiesExtractor.extract(actual, byName(fieldOrProperty));522 return new ObjectArrayAssert<>(values);523 }524 /**525 * Extract the values of given fields/properties from the array's elements under test into a new array composed of526 * Tuple (a simple data structure), this new array becoming the array under test.527 * <p/>528 * It allows you to test fields/properties of the the array's elements instead of testing the elements themselves, it529 * can be sometimes much less work !530 * <p/>531 * The Tuple data corresponds to the extracted values of the given fields/properties, for instance if you ask to532 * extract "id", "name" and "email" then each Tuple data will be composed of id, name and email extracted from the533 * element of the initial array (the Tuple's data order is the same as the given fields/properties order).534 * <p/>535 * Let's take an example to make things clearer :536 * <pre><code class='java'> // Build an array of TolkienCharacter, a TolkienCharacter has a name (String) and a Race (a class)537 * // they can be public field or properties, both works when extracting their values.538 * TolkienCharacter[] fellowshipOfTheRing = new TolkienCharacter[] {539 * new TolkienCharacter("Frodo", 33, HOBBIT),540 * new TolkienCharacter("Sam", 38, HOBBIT),541 * new TolkienCharacter("Gandalf", 2020, MAIA),542 * new TolkienCharacter("Legolas", 1000, ELF),543 * new TolkienCharacter("Pippin", 28, HOBBIT),544 * new TolkienCharacter("Gimli", 139, DWARF),545 * new TolkienCharacter("Aragorn", 87, MAN,546 * new TolkienCharacter("Boromir", 37, MAN)547 * };548 * 549 * // let's verify 'name' and 'age' of some TolkienCharacter in fellowshipOfTheRing :550 * 551 * assertThat(fellowshipOfTheRing).extracting("name", "age")552 * .contains(tuple("Boromir", 37),553 * tuple("Sam", 38),554 * tuple("Legolas", 1000));555 * 556 * 557 * // extract 'name', 'age' and Race name values.558 * 559 * assertThat(fellowshipOfTheRing).extracting("name", "age", "race.name")560 * .contains(tuple("Boromir", 37, "Man"),561 * tuple("Sam", 38, "Hobbit"),562 * tuple("Legolas", 1000, "Elf"));</code></pre>563 * 564 * A property with the given name is looked for first, if it does not exist the a field with the given name is565 * looked for.566 * <p/>567 * Note that the order of extracted property/field values is consistent with the iteration order of the array under568 * test.569 *570 * @param propertiesOrFields the properties/fields to extract from the initial array under test571 * @return a new assertion object whose object under test is the list of Tuple with extracted properties/fields values572 * as data.573 * @throws IntrospectionError if one of the given name does not match a field or property in one of the initial574 * Iterable's element.575 */576 public ObjectArrayAssert<Tuple> extracting(String... propertiesOrFields) {577 Object[] values = FieldsOrPropertiesExtractor.extract(actual, byName(propertiesOrFields));578 Tuple[] result = Arrays.copyOf(values, values.length, Tuple[].class);579 return new ObjectArrayAssert<>(result);580 }581 /**582 * Extract the values from arrays's elements after test by applying an extracting function on them. The returned583 * array becomes a new object under test.584 * <p/>585 * It allows to test values from the elements in more safe way than by using {@link #extracting(String)}, as it586 * doesn't utilize introspection.587 * <p/>588 * Let's take a look an example589 * <pre><code class='java'> // Build a list of TolkienCharacter, a TolkienCharacter has a name, and age and a Race (a specific class)590 * // they can be public field or properties, both can be extracted.591 * List<TolkienCharacter> fellowshipOfTheRing = new ArrayList<TolkienCharacter>();592 * 593 * fellowshipOfTheRing.add(new TolkienCharacter("Frodo", 33, HOBBIT));594 * fellowshipOfTheRing.add(new TolkienCharacter("Sam", 38, HOBBIT));595 * fellowshipOfTheRing.add(new TolkienCharacter("Gandalf", 2020, MAIA));596 * fellowshipOfTheRing.add(new TolkienCharacter("Legolas", 1000, ELF));597 * fellowshipOfTheRing.add(new TolkienCharacter("Pippin", 28, HOBBIT));598 * fellowshipOfTheRing.add(new TolkienCharacter("Gimli", 139, DWARF));599 * fellowshipOfTheRing.add(new TolkienCharacter("Aragorn", 87, MAN);600 * fellowshipOfTheRing.add(new TolkienCharacter("Boromir", 37, MAN));601 * 602 * // this extracts the race603 * Extractor<TolkienCharacter, Race> race = new Extractor<TolkienCharacter, Race>() {604 * @Override605 * public Race extract(TolkienCharacter input) {606 * return input.getRace();607 * }608 * }609 * 610 * // fellowship has hobbitses, right, my presioussss?611 * assertThat(fellowshipOfTheRing).extracting(race).contains(HOBBIT);</code></pre>612 * 613 * Note that the order of extracted property/field values is consistent with the iteration order of the Iterable under614 * test, for example if it's a {@link HashSet}, you won't be able to make any assumptions on the extracted values615 * order.616 * 617 * @param extractor the object transforming input object to desired one618 * @return a new assertion object whose object under test is the list of values extracted619 */620 public <U> ObjectArrayAssert<U> extracting(Extractor<? super T, U> extractor) {621 U[] extracted = FieldsOrPropertiesExtractor.extract(actual, extractor);622 return new ObjectArrayAssert<>(extracted);623 }624 /**625 * Extract the Iterable values from arrays elements under test by applying an Iterable extracting function on them626 * and concatenating the result lists into an array which becomes the new object under test.627 * <p/>628 * It allows testing the results of extracting values that are represented by Iterables.629 * <p/>630 * For example:631 * <pre><code class='java'> CartoonCharacter bart = new CartoonCharacter("Bart Simpson");632 * CartoonCharacter lisa = new CartoonCharacter("Lisa Simpson");633 * CartoonCharacter maggie = new CartoonCharacter("Maggie Simpson");634 * CartoonCharacter homer = new CartoonCharacter("Homer Simpson");635 * homer.addChildren(bart, lisa, maggie);636 * 637 * CartoonCharacter pebbles = new CartoonCharacter("Pebbles Flintstone");638 * CartoonCharacter fred = new CartoonCharacter("Fred Flintstone");639 * fred.getChildren().add(pebbles);640 * 641 * Extractor<CartoonCharacter, List<CartoonCharacter>> childrenOf = new Extractor<CartoonCharacter, List<CartoonCharacter>>() {642 * @Override643 * public List<CartoonChildren> extract(CartoonCharacter input) {644 * return input.getChildren();645 * }646 * }647 * 648 * CartoonCharacter[] parents = new CartoonCharacter[] { homer, fred };649 * // check children650 * assertThat(parents).flatExtracting(childrenOf)651 * .containsOnly(bart, lisa, maggie, pebbles);</code></pre>652 * 653 * The order of extracted values is consisted with both the order of the collection itself, as well as the extracted654 * collections.655 * 656 * @param extractor the object transforming input object to an Iterable of desired ones657 * @return a new assertion object whose object under test is the list of values extracted658 */659 public <U, C extends Collection<U>> ObjectArrayAssert<U> flatExtracting(Extractor<? super T, C> extractor) {660 final List<C> extractedValues = FieldsOrPropertiesExtractor.extract(Arrays.asList(actual), extractor);661 final List<U> result = newArrayList();662 for (C e : extractedValues) {663 result.addAll(e);664 }665 return new ObjectArrayAssert<>(IterableUtil.toArray(result));666 }667 /**668 * Extract from array's elements the Iterable/Array values corresponding to the given property/field name and669 * concatenate them into a single array becoming the new object under test.670 * <p/>671 * It allows testing the elements of extracting values that are represented by iterables or arrays.672 * <p/>673 * For example:674 * <pre><code class='java'> CartoonCharacter bart = new CartoonCharacter("Bart Simpson");675 * CartoonCharacter lisa = new CartoonCharacter("Lisa Simpson");676 * CartoonCharacter maggie = new CartoonCharacter("Maggie Simpson");677 * CartoonCharacter homer = new CartoonCharacter("Homer Simpson");678 * homer.addChildren(bart, lisa, maggie);679 *680 * CartoonCharacter pebbles = new CartoonCharacter("Pebbles Flintstone");681 * CartoonCharacter fred = new CartoonCharacter("Fred Flintstone");682 * fred.getChildren().add(pebbles);683 *684 * CartoonCharacter[] parents = new CartoonCharacter[] { homer, fred };685 * // check children686 * assertThat(parents).flatExtracting("children")687 * .containsOnly(bart, lisa, maggie, pebbles);</code></pre>688 *689 * The order of extracted values is consisted with both the order of the collection itself, as well as the extracted690 * collections.691 *692 * @param propertyName the object transforming input object to an Iterable of desired ones693 * @return a new assertion object whose object under test is the list of values extracted694 * @throws IllegalArgumentException if one of the extracted property value was not an array or an iterable.695 */696 public ObjectArrayAssert<Object> flatExtracting(String propertyName) {697 List<Object> extractedValues = newArrayList();698 List<?> extractedGroups = FieldsOrPropertiesExtractor.extract(Arrays.asList(actual), byName(propertyName));699 for (Object group : extractedGroups) {700 // expecting group to be an iterable or an array701 if (isArray(group)) {702 int size = Array.getLength(group);703 for (int i = 0; i < size; i++) {704 extractedValues.add(Array.get(group, i));705 }706 } else if (group instanceof Iterable) {707 Iterable<?> iterable = (Iterable<?>) group;708 for (Object value : iterable) {709 extractedValues.add(value);710 }711 } else {712 CommonErrors.wrongElementTypeForFlatExtracting(group);713 }714 }715 return new ObjectArrayAssert<>(extractedValues.toArray());716 }717 /**718 * Extract the result of given method invocation from the array's elements under test into a new array, this new array719 * becoming the array under test.720 * <p>721 * It allows you to test a method results of the array's elements instead of testing the elements themselves, it can be722 * sometimes much less work!723 * <p>724 * It is especially useful for classes that does not conform to Java Bean's getter specification (i.e. public String725 * toString() or public String status() instead of public String getStatus()).726 * <p>727 * Let's take an example to make things clearer :728 * <pre><code class='java'> // Build a array of WesterosHouse, a WesterosHouse has a method: public String sayTheWords()729 * WesterosHouse[] greatHousesOfWesteros = new WesterosHouse[] { new WesterosHouse("Stark", "Winter is Coming"),730 * new WesterosHouse("Lannister", "Hear Me Roar!"), new WesterosHouse("Greyjoy", "We Do Not Sow"),731 * new WesterosHouse("Baratheon", "Our is the Fury"), new WesterosHouse("Martell", "Unbowed, Unbent, Unbroken"),732 * new WesterosHouse("Tyrell", "Growing Strong") };733 * 734 * // let's verify the words of great houses in Westeros:735 * 736 * assertThat(greatHousesOfWesteros).extractingResultOf("sayTheWords")737 * .contains("Winter is Coming", "We Do Not Sow", "Hear Me Roar")738 * .doesNotContain("Lannisters always pay their debts");</code></pre>739 * 740 * <p>741 * Following requirements have to be met to extract method results:742 * <ul>743 * <li>method has to be public,</li>744 * <li>method cannot accept any arguments,</li>745 * <li>method cannot return void.</li>746 * </ul>747 * <p>748 * Note that the order of extracted values is consistent with the order of the array under test.749 * 750 * @param method the name of the method which result is to be extracted from the array under test751 * @return a new assertion object whose object under test is the array of extracted values.752 * @throws IllegalArgumentException if no method exists with the given name, or method is not public, or method does753 * return void, or method accepts arguments.754 */755 public ObjectArrayAssert<Object> extractingResultOf(String method) {756 Object[] values = FieldsOrPropertiesExtractor.extract(actual, resultOf(method));757 return new ObjectArrayAssert<>(values);758 }759 /**760 * Extract the result of given method invocation from the array's elements under test into a new array, this new array761 * becoming the array under test.762 * <p>763 * It allows you to test a method results of the array's elements instead of testing the elements themselves, it can be764 * sometimes much less work!765 * <p>766 * It is especially useful for classes that does not conform to Java Bean's getter specification (i.e. public String767 * toString() or public String status() instead of public String getStatus()).768 * <p>769 * Let's take an example to make things clearer :770 * <pre><code class='java'> // Build a array of WesterosHouse, a WesterosHouse has a method: public String sayTheWords()771 * WesterosHouse[] greatHousesOfWesteros = new WesterosHouse[] { new WesterosHouse("Stark", "Winter is Coming"),772 * new WesterosHouse("Lannister", "Hear Me Roar!"), new WesterosHouse("Greyjoy", "We Do Not Sow"),773 * new WesterosHouse("Baratheon", "Our is the Fury"), new WesterosHouse("Martell", "Unbowed, Unbent, Unbroken"),774 * new WesterosHouse("Tyrell", "Growing Strong") };775 * 776 * // let's verify the words of great houses in Westeros:777 * 778 * assertThat(greatHousesOfWesteros).extractingResultOf("sayTheWords", String.class)779 * .contains("Winter is Coming", "We Do Not Sow", "Hear Me Roar")780 * .doesNotContain("Lannisters always pay their debts");</code></pre>781 * 782 * <p>783 * Following requirements have to be met to extract method results:784 * <ul>785 * <li>method has to be public,</li>786 * <li>method can not accept any arguments,</li>787 * <li>method can not return void.</li>788 * </ul>789 * <p>790 * Note that the order of extracted values is consistent with the order of the array under test.791 * 792 * @param method the name of the method which result is to be extracted from the array under test793 * @param extractingType type to return794 * @return a new assertion object whose object under test is the array of extracted values.795 * @throws IllegalArgumentException if no method exists with the given name, or method is not public, or method does796 * return void, or method accepts arguments.797 */798 public <P> ObjectArrayAssert<P> extractingResultOf(String method, Class<P> extractingType) {799 @SuppressWarnings("unchecked")800 P[] values = (P[]) FieldsOrPropertiesExtractor.extract(actual, resultOf(method));801 return new ObjectArrayAssert<>(values);802 }803 /**804 * Enable hexadecimal object representation of Iterable elements instead of standard java representation in error805 * messages.806 * <p/>807 * It can be useful to better understand what the error was with a more meaningful error message.808 * <p/>809 * Example810 * <pre><code class='java'> assertThat(new Byte[] { 0x10, 0x20 }).inHexadecimal().contains(new Byte[] { 0x30 });</code></pre>811 *812 * With standard error message:813 * <pre><code class='java'> Expecting:814 * <[16, 32]>815 * to contain:816 * <[48]>817 * but could not find:818 * <[48]></code></pre>819 *820 * With Hexadecimal error message:821 * <pre><code class='java'> Expecting:822 * <[0x10, 0x20]>823 * to contain:824 * <[0x30]>825 * but could not find:826 * <[0x30]></code></pre>827 *828 * @return {@code this} assertion object.829 */830 @Override831 public S inHexadecimal() {832 return super.inHexadecimal();833 }834 @Override835 public S inBinary() {836 return super.inBinary();837 }838 /**839 * Filter the array under test keeping only elements having a property or field equal to {@code expectedValue}, the840 * property/field is specified by {@code propertyOrFieldName} parameter.841 * <p>842 * The filter first tries to get the value from a property (named {@code propertyOrFieldName}), if no such property843 * exists it tries to read the value from a field. Reading private fields is supported by default, this can be844 * globally disabled by calling {@link Assertions#setAllowExtractingPrivateFields(boolean)845 * Assertions.setAllowExtractingPrivateFields(false)}.846 * <p>847 * When reading <b>nested</b> property/field, if an intermediate value is null the whole nested property/field is848 * considered to be null, thus reading "address.street.name" value will return null if "street" value is null.849 * <p>850 * 851 * As an example, let's check all employees 800 years old (yes, special employees):852 * <pre><code class='java'> Employee yoda = new Employee(1L, new Name("Yoda"), 800);853 * Employee obiwan = new Employee(2L, new Name("Obiwan"), 800);854 * Employee luke = new Employee(3L, new Name("Luke", "Skywalker"), 26);855 * Employee noname = new Employee(4L, null, 50);856 * 857 * Employee[] employees = new Employee[] { yoda, luke, obiwan, noname };858 *859 * assertThat(employees).filteredOn("age", 800)860 * .containsOnly(yoda, obiwan);</code></pre>861 * 862 * Nested properties/fields are supported:863 * <pre><code class='java'> // Name is bean class with 'first' and 'last' String properties864 *865 * // name is null for noname => it does not match the filter on "name.first" 866 * assertThat(employees).filteredOn("name.first", "Luke")867 * .containsOnly(luke);868 * 869 * assertThat(employees).filteredOn("name.last", "Vader")870 * .isEmpty();</code></pre>871 * <p>872 * If you want to filter on null value, use {@link #filteredOnNull(String)} as Java will resolve the call to873 * {@link #filteredOn(String, FilterOperator)} instead of this method.874 * <p>875 * An {@link IntrospectionError} is thrown if the given propertyOrFieldName can't be found in one of the array876 * elements.877 * <p>878 * You can chain filters:879 * <pre><code class='java'> // fellowshipOfTheRing is an array of TolkienCharacter having race and name fields880 * // 'not' filter is statically imported from Assertions.not 881 * 882 * assertThat(fellowshipOfTheRing).filteredOn("race.name", "Man")883 * .filteredOn("name", not("Boromir"))884 * .containsOnly(aragorn);</code></pre>885 * If you need more complex filter, use {@link #filteredOn(Condition)} and provide a {@link Condition} to specify the886 * filter to apply.887 * 888 * @param propertyOrFieldName the name of the property or field to read889 * @param expectedValue the value to compare element's property or field with890 * @return a new assertion object with the filtered array under test891 * @throws IllegalArgumentException if the given propertyOrFieldName is {@code null} or empty.892 * @throws IntrospectionError if the given propertyOrFieldName can't be found in one of the array elements.893 */894 @SuppressWarnings("unchecked")895 public S filteredOn(String propertyOrFieldName, Object expectedValue) {896 Iterable<? extends T> filteredIterable = filter(actual).with(propertyOrFieldName, expectedValue).get();897 return (S) new ObjectArrayAssert<>(toArray(filteredIterable));898 }899 /**900 * Filter the array under test keeping only elements whose property or field specified by {@code propertyOrFieldName}901 * is null.902 * <p>903 * exists it tries to read the value from a field. Reading private fields is supported by default, this can be...
Source:AbstractObjectAssert.java
...63 * It means that if an actual field is not null and the corresponding field in other is null, this field will be64 * ignored in comparison, but the opposite will make assertion fail (null field in actual, not null in other) as65 * the field is used in the performed comparison and the values differ.66 * <p>67 * Note that comparison is <b>not</b> recursive, if one of the field is an Object, it will be compared to the other68 * field using its {@code equals} method.69 * <p>70 * If an object has a field and a property with the same name, the property value will be used over the field.71 * <p>72 * Private fields are used in comparison but this can be disabled using73 * {@link Assertions#setAllowComparingPrivateFields(boolean)}, if disabled only <b>accessible</b> fields values are74 * compared, accessible fields include directly accessible fields (e.g. public) or fields with an accessible getter.75 * <p>76 * The objects to compare can be of different types but the properties/fields used in comparison must exist in both,77 * for example if actual object has a name String field, it is expected other object to also have one.78 * <p>79 *80 * Example:81 * <pre><code class='java'> TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT);82 * TolkienCharacter mysteriousHobbit = new TolkienCharacter(null, 33, HOBBIT);83 *84 * // Null fields in other/expected object are ignored, the mysteriousHobbit has null name thus name is ignored85 * assertThat(frodo).isEqualToIgnoringNullFields(mysteriousHobbit); // OK86 *87 * // ... but this is not reversible !88 * assertThat(mysteriousHobbit).isEqualToIgnoringNullFields(frodo); // FAIL</code></pre>89 *90 * @param other the object to compare {@code actual} to.91 * @return {@code this} assertion object.92 * @throws NullPointerException if the actual or other object is {@code null}.93 * @throws AssertionError if the actual and the given object are not lenient equals.94 * @throws IntrospectionError if one of actual's field to compare can't be found in the other object.95 */96 public SELF isEqualToIgnoringNullFields(Object other) {97 objects.assertIsEqualToIgnoringNullFields(info, actual, other, comparatorByPropertyOrField, comparatorByType);98 return myself;99 }100 /**101 * Assert that the actual object is equal to the given one using a property/field by property/field comparison <b>on the given properties/fields only</b>102 * (fields can be inherited fields or nested fields). This can be handy if {@code equals} implementation of objects to compare does not suit you.103 * <p>104 * Note that comparison is <b>not</b> recursive, if one of the field is an Object, it will be compared to the other105 * field using its {@code equals} method.106 * <p>107 * If an object has a field and a property with the same name, the property value will be used over the field.108 * <p>109 * Private fields are used in comparison but this can be disabled using110 * {@link Assertions#setAllowComparingPrivateFields(boolean)}, if disabled only <b>accessible </b>fields values are111 * compared, accessible fields include directly accessible fields (e.g. public) or fields with an accessible getter.112 * <p>113 * The objects to compare can be of different types but the properties/fields used in comparison must exist in both,114 * for example if actual object has a name String field, it is expected the other object to also have one.115 * <p>116 *117 * Example:118 * <pre><code class='java'> TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT);119 * TolkienCharacter sam = new TolkienCharacter("Sam", 38, HOBBIT);120 *121 * // frodo and sam both are hobbits, so they are equals when comparing only race122 * assertThat(frodo).isEqualToComparingOnlyGivenFields(sam, "race"); // OK123 *124 * // they are also equals when comparing only race name (nested field).125 * assertThat(frodo).isEqualToComparingOnlyGivenFields(sam, "race.name"); // OK126 *127 * // ... but not when comparing both name and race128 * assertThat(frodo).isEqualToComparingOnlyGivenFields(sam, "name", "race"); // FAIL</code></pre>129 *130 * @param other the object to compare {@code actual} to.131 * @param propertiesOrFieldsUsedInComparison properties/fields used in comparison.132 * @return {@code this} assertion object.133 * @throws NullPointerException if the actual or other is {@code null}.134 * @throws AssertionError if the actual and the given objects are not equals property/field by property/field on given fields.135 * @throws IntrospectionError if one of actual's property/field to compare can't be found in the other object.136 * @throws IntrospectionError if a property/field does not exist in actual.137 */138 public SELF isEqualToComparingOnlyGivenFields(Object other, String... propertiesOrFieldsUsedInComparison) {139 objects.assertIsEqualToComparingOnlyGivenFields(info, actual, other, comparatorByPropertyOrField, comparatorByType,140 propertiesOrFieldsUsedInComparison);141 return myself;142 }143 /**144 * Assert that the actual object is equal to the given one by comparing their properties/fields <b>except for the given ones</b>145 * (inherited ones are taken into account). This can be handy if {@code equals} implementation of objects to compare does not suit you.146 * <p>147 * Note that comparison is <b>not</b> recursive, if one of the property/field is an Object, it will be compared to the other148 * field using its {@code equals} method.149 * <p>150 * If an object has a field and a property with the same name, the property value will be used over the field.151 * <p>152 * Private fields are used in comparison but this can be disabled using153 * {@link Assertions#setAllowComparingPrivateFields(boolean)}, if disabled only <b>accessible </b>fields values are154 * compared, accessible fields include directly accessible fields (e.g. public) or fields with an accessible getter.155 * <p>156 * The objects to compare can be of different types but the properties/fields used in comparison must exist in both,157 * for example if actual object has a name String field, it is expected the other object to also have one.158 * <p>159 *160 * Example:161 * <pre><code class='java'> TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT);162 * TolkienCharacter sam = new TolkienCharacter("Sam", 38, HOBBIT);163 *164 * // frodo and sam are equals when ignoring name and age since the only remaining field is race which they share as HOBBIT.165 * assertThat(frodo).isEqualToIgnoringGivenFields(sam, "name", "age"); // OK166 *167 * // ... but they are not equals if only age is ignored as their names differ.168 * assertThat(frodo).isEqualToIgnoringGivenFields(sam, "age"); // FAIL</code></pre>169 *170 * @param other the object to compare {@code actual} to.171 * @param propertiesOrFieldsToIgnore ignored properties/fields to ignore in comparison.172 * @return {@code this} assertion object.173 * @throws NullPointerException if the actual or given object is {@code null}.174 * @throws AssertionError if the actual and the given objects are not equals property/field by property/field after ignoring given fields.175 * @throws IntrospectionError if one of actual's property/field to compare can't be found in the other object.176 */177 public SELF isEqualToIgnoringGivenFields(Object other, String... propertiesOrFieldsToIgnore) {178 objects.assertIsEqualToIgnoringGivenFields(info, actual, other, comparatorByPropertyOrField, comparatorByType,179 propertiesOrFieldsToIgnore);180 return myself;181 }182 /**183 * Assert that the actual object has no null fields or properties (inherited ones are taken into account).184 * <p>185 * If an object has a field and a property with the same name, the property value will be used over the field.186 * <p>187 * Private fields are checked but this can be disabled using {@link Assertions#setAllowComparingPrivateFields(boolean)},188 * if disabled only <b>accessible </b>fields values are189 * checked, accessible fields include directly accessible fields (e.g. public) or fields with an accessible getter.190 * <p>191 *192 * Example:193 * <pre><code class='java'> TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT);194 * TolkienCharacter sam = new TolkienCharacter("Sam", 38, null);195 *196 * // assertion succeeds since all frodo's fields are set197 * assertThat(frodo).hasNoNullFields();198 *199 * // assertion succeeds because sam does not have its race set200 * assertThat(sam).hasNoNullFields();</code></pre>201 *202 * @return {@code this} assertion object.203 * @throws AssertionError if the actual object is {@code null}.204 * @throws AssertionError if some fields or properties of the actual object are null.205 * 206 * @since 2.5.0 / 3.5.0207 */208 public SELF hasNoNullFieldsOrProperties() {209 objects.assertHasNoNullFieldsOrPropertiesExcept(info, actual);210 return myself;211 }212 /**213 * Assert that the actual object has no null fields or properties <b>except for the given ones</b>214 * (inherited ones are taken into account).215 * <p>216 * If an object has a field and a property with the same name, the property value will be used over the field.217 * <p>218 * Private fields are checked but this can be disabled using {@link Assertions#setAllowComparingPrivateFields(boolean)},219 * if disabled only <b>accessible </b>fields values are220 * checked, accessible fields include directly accessible fields (e.g. public) or fields with an accessible getter.221 * <p>222 * Example:223 * <pre><code class='java'> TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, null);224 *225 * // assertion succeeds since frodo has only null field is race226 * assertThat(frodo).hasNoNullFieldsExcept("race");227 *228 * // ... but if we require the race field, the assertion fails229 * assertThat(frodo).hasNoNullFieldsExcept("name", "age");</code></pre>230 *231 * @param propertiesOrFieldsToIgnore properties/fields that won't be checked for null.232 * @return {@code this} assertion object.233 * @throws AssertionError if the actual object is {@code null}.234 * @throws AssertionError if some (non ignored) fields or properties of the actual object are null.235 * 236 * @since 2.5.0 / 3.5.0237 */238 public SELF hasNoNullFieldsOrPropertiesExcept(String... propertiesOrFieldsToIgnore) {239 objects.assertHasNoNullFieldsOrPropertiesExcept(info, actual, propertiesOrFieldsToIgnore);240 return myself;241 }242 /**243 * Assert that actual object is equal to the given object based on a property/field by property/field comparison (including244 * inherited ones). This can be handy if {@code equals} implementation of objects to compare does not suit you.245 * <p>246 * Note that comparison is <b>not</b> recursive, if one of the field is an Object, it will be compared to the other247 * field using its {@code equals} method.248 * <p>249 * If an object has a field and a property with the same name, the property value will be used over the field.250 * <p>251 * Private fields are used in comparison but this can be disabled using252 * {@link Assertions#setAllowComparingPrivateFields(boolean)}, if disabled only <b>accessible </b>fields values are253 * compared, accessible fields include directly accessible fields (e.g. public) or fields with an accessible getter.254 * <p>255 * The objects to compare can be of different types but the properties/fields used in comparison must exist in both,256 * for example if actual object has a name String field, it is expected the other object to also have one.257 * <p>258 *259 * Example:260 * <pre><code class='java'> // equals not overridden in TolkienCharacter261 * TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT);262 * TolkienCharacter frodoClone = new TolkienCharacter("Frodo", 33, HOBBIT);263 *264 * // Fail as equals compares object references265 * assertThat(frodo).isEqualsTo(frodoClone);266 *267 * // frodo and frodoClone are equals when doing a field by field comparison.268 * assertThat(frodo).isEqualToComparingFieldByField(frodoClone);</code></pre>269 *270 * @param other the object to compare {@code actual} to.271 * @return {@code this} assertions object272 * @throws AssertionError if the actual object is {@code null}.273 * @throws AssertionError if the actual and the given objects are not equals property/field by property/field.274 * @throws IntrospectionError if one of actual's property/field to compare can't be found in the other object.275 */276 public SELF isEqualToComparingFieldByField(Object other) {277 objects.assertIsEqualToIgnoringGivenFields(info, actual, other, comparatorByPropertyOrField, comparatorByType);278 return myself;279 }280 /**281 * Allows to set a specific comparator to compare properties or fields with the given names.282 * A typical usage is for comparing double/float fields with a given precision.283 * <p>284 * Comparators specified by this method have precedence over comparators added by {@link #usingComparatorForType}.285 * <p>286 * The comparators specified by this method are only used for field by field comparison like {@link #isEqualToComparingFieldByField(Object)}.287 * <p>288 * When used with {@link #isEqualToComparingFieldByFieldRecursively(Object)}, the fields/properties must be specified from the root object, 289 * for example if Foo class as a Bar field and Bar class has an id, to set a comparator for Bar's id use {@code "bar.id"}. 290 * <p>291 * Example:292 * <pre><code class='java'> public class TolkienCharacter {293 * private String name;294 * private double height;295 * // constructor omitted296 * }297 * TolkienCharacter frodo = new TolkienCharacter("Frodo", 1.2);298 * TolkienCharacter tallerFrodo = new TolkienCharacter("Frodo", 1.3);299 * TolkienCharacter reallyTallFrodo = new TolkienCharacter("Frodo", 1.9);300 *301 * Comparator<Double> closeEnough = new Comparator<Double>() {302 * double precision = 0.5;303 * public int compare(Double d1, Double d2) {304 * return Math.abs(d1 - d2) <= precision ? 0 : 1;305 * }306 * };307 *308 * // assertions will pass309 * assertThat(frodo).usingComparatorForFields(closeEnough, "height")310 * .isEqualToComparingFieldByField(tallerFrodo);311 *312 * assertThat(frodo).usingComparatorForFields(closeEnough, "height")313 * .isEqualToIgnoringNullFields(tallerFrodo);314 *315 * assertThat(frodo).usingComparatorForFields(closeEnough, "height")316 * .isEqualToIgnoringGivenFields(tallerFrodo);317 *318 * assertThat(frodo).usingComparatorForFields(closeEnough, "height")319 * .isEqualToComparingOnlyGivenFields(tallerFrodo);320 *321 * // assertion will fail322 * assertThat(frodo).usingComparatorForFields(closeEnough, "height")323 * .isEqualToComparingFieldByField(reallyTallFrodo);</code></pre>324 *325 * @param comparator the {@link java.util.Comparator} to use326 * @param propertiesOrFields the names of the properties and/or fields the comparator should be used for327 * @return {@code this} assertions object328 */329 @CheckReturnValue330 public <T> SELF usingComparatorForFields(Comparator<T> comparator, String... propertiesOrFields) {331 for (String propertyOrField : propertiesOrFields) {332 comparatorByPropertyOrField.put(propertyOrField, comparator);333 }334 return myself;335 }336 /**337 * Allows to set a specific comparator to compare properties or fields with the given type.338 * A typical usage is for comparing fields of numeric type at a given precision.339 * <p>340 * Comparators specified by {@link #usingComparatorForFields} have precedence over comparators specified by this method.341 * <p>342 * The comparators specified by this method are only used for field by field comparison like {@link #isEqualToComparingFieldByField(Object)}.343 * <p>344 * Example:345 * <pre><code class='java'> public class TolkienCharacter {346 * private String name;347 * private double height;348 * // constructor omitted349 * }350 * TolkienCharacter frodo = new TolkienCharacter("Frodo", 1.2);351 * TolkienCharacter tallerFrodo = new TolkienCharacter("Frodo", 1.3);352 * TolkienCharacter reallyTallFrodo = new TolkienCharacter("Frodo", 1.9);353 *354 * Comparator<Double> closeEnough = new Comparator<Double>() {355 * double precision = 0.5;356 * public int compare(Double d1, Double d2) {357 * return Math.abs(d1 - d2) <= precision ? 0 : 1;358 * }359 * };360 *361 * // assertions will pass362 * assertThat(frodo).usingComparatorForType(closeEnough, Double.class)363 * .isEqualToComparingFieldByField(tallerFrodo);364 *365 * assertThat(frodo).usingComparatorForType(closeEnough, Double.class)366 * .isEqualToIgnoringNullFields(tallerFrodo);367 *368 * assertThat(frodo).usingComparatorForType(closeEnough, Double.class)369 * .isEqualToIgnoringGivenFields(tallerFrodo);370 *371 * assertThat(frodo).usingComparatorForType(closeEnough, Double.class)372 * .isEqualToComparingOnlyGivenFields(tallerFrodo);373 *374 * // assertion will fail375 * assertThat(frodo).usingComparatorForType(closeEnough, Double.class)376 * .isEqualToComparingFieldByField(reallyTallFrodo);</code></pre>377 *378 * If multiple compatible comparators have been registered for a given {@code type}, the closest in the inheritance 379 * chain to the given {@code type} is chosen in the following order:380 * <ol>381 * <li>The comparator for the exact given {@code type}</li>382 * <li>The comparator of a superclass of the given {@code type}</li>383 * <li>The comparator of an interface implemented by the given {@code type}</li>384 * </ol>385 *386 * @param comparator the {@link java.util.Comparator} to use387 * @param type the {@link java.lang.Class} of the type the comparator should be used for388 * @param <T> the type of objects that the comparator should be used for389 * @return {@code this} assertions object390 */391 @CheckReturnValue392 public <T> SELF usingComparatorForType(Comparator<? super T> comparator, Class<T> type) {393 comparatorByType.put(type, comparator);394 return myself;395 }396 /**397 * Assert that the actual object has the specified field or property.398 * <p>399 * Private fields are matched by default but this can be changed by calling {@link Assertions#setAllowExtractingPrivateFields(boolean) Assertions.setAllowExtractingPrivateFields(false)}.400 * <p>401 *402 * Example:403 * <pre><code class='java'> public class TolkienCharacter {404 *405 * private String name;406 * private int age;407 * // constructor omitted408 *409 * public String getName() {410 * return this.name;411 * }412 * }413 *414 * TolkienCharacter frodo = new TolkienCharacter("Frodo", 33);415 *416 * // assertions will pass :417 * assertThat(frodo).hasFieldOrProperty("name")418 * .hasFieldOrProperty("age"); // private field are matched by default419 *420 * // assertions will fail :421 * assertThat(frodo).hasFieldOrProperty("not_exists");422 * assertThat(frodo).hasFieldOrProperty(null);423 * // disable looking for private fields424 * Assertions.setAllowExtractingPrivateFields(false);425 * assertThat(frodo).hasFieldOrProperty("age"); </code></pre>426 *427 * @param name the field/property name to check428 * @return {@code this} assertion object.429 * @throws AssertionError if the actual object is {@code null}.430 * @throws IllegalArgumentException if name is {@code null}.431 * @throws AssertionError if the actual object has not the given field/property432 */433 public SELF hasFieldOrProperty(String name) {434 objects.assertHasFieldOrProperty(info, actual, name);435 return myself;436 }437 /**438 * Assert that the actual object has the specified field or property with the given value.439 * <p>440 * Private fields are matched by default but this can be changed by calling {@link Assertions#setAllowExtractingPrivateFields(boolean) Assertions.setAllowExtractingPrivateFields(false)}.441 * <p>442 *443 * Example:444 * <pre><code class='java'> public class TolkienCharacter {445 * private String name;446 * private int age;447 * // constructor omitted448 *449 * public String getName() {450 * return this.name;451 * }452 * }453 *454 * TolkienCharacter frodo = new TolkienCharacter("Frodo", 33);455 * TolkienCharacter noname = new TolkienCharacter(null, 33);456 *457 * // assertions will pass :458 * assertThat(frodo).hasFieldOrProperty("name", "Frodo");459 * assertThat(frodo).hasFieldOrProperty("age", 33);460 * assertThat(noname).hasFieldOrProperty("name", null);461 *462 * // assertions will fail :463 * assertThat(frodo).hasFieldOrProperty("name", "not_equals");464 * assertThat(frodo).hasFieldOrProperty(null, 33);465 * assertThat(frodo).hasFieldOrProperty("age", null);466 * assertThat(noname).hasFieldOrProperty("name", "Frodo");467 * // disable extracting private fields468 * Assertions.setAllowExtractingPrivateFields(false);469 * assertThat(frodo).hasFieldOrProperty("age", 33); </code></pre>470 *471 * @param name the field/property name to check472 * @param value the field/property expected value473 * @return {@code this} assertion object.474 * @throws AssertionError if the actual object is {@code null}.475 * @throws IllegalArgumentException if name is {@code null}.476 * @throws AssertionError if the actual object has not the given field/property477 * @throws AssertionError if the actual object has the given field/property but not with the expected value478 *479 * @see AbstractObjectAssert#hasFieldOrProperty(java.lang.String)480 */481 public SELF hasFieldOrPropertyWithValue(String name, Object value) {482 objects.assertHasFieldOrPropertyWithValue(info, actual, name, value);483 return myself;484 }485 /**486 * Extract the values of given fields/properties from the object under test into an array, this new array becoming487 * the object under test.488 * <p>489 * If you extract "id", "name" and "email" fields/properties then the array will contain the id, name and email values490 * of the object under test, you can then perform array assertions on the extracted values.491 * <p>492 * Nested fields/properties are supported, specifying "adress.street.number" is equivalent to get the value493 * corresponding to actual.getAdress().getStreet().getNumber()494 * <p>495 * Private fields can be extracted unless you call {@link Assertions#setAllowExtractingPrivateFields(boolean) Assertions.setAllowExtractingPrivateFields(false)}.496 * <p>497 * If the object under test is a {@link Map} with {@link String} keys, extracting will extract values matching the given fields/properties. 498 * <p>499 * Example:500 * <pre><code class='java'> // Create frodo, setting its name, age and Race fields (Race having a name field)501 * TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT);502 *503 * // let's verify Frodo's name, age and race name:504 * assertThat(frodo).extracting("name", "age", "race.name")505 * .containsExactly("Frodo", 33, "Hobbit");</code></pre>506 *507 * A property with the given name is looked for first, if it doesn't exist then a field with the given name is looked508 * for, if the field is not accessible (i.e. does not exist) an IntrospectionError is thrown.509 * <p>510 * Note that the order of extracted property/field values is consistent with the iteration order of the array under511 * test.512 *513 * @param propertiesOrFields the properties/fields to extract from the initial object under test514 * @return a new assertion object whose object under test is the array containing the extracted properties/fields values515 * @throws IntrospectionError if one of the given name does not match a field or property516 */517 @CheckReturnValue518 public AbstractObjectArrayAssert<?, Object> extracting(String... propertiesOrFields) {519 Tuple values = byName(propertiesOrFields).extract(actual);520 return extracting(values.toList(), propertiesOrFields);521 }522 AbstractObjectArrayAssert<?, Object> extracting(List<Object> values, String... propertiesOrFields) {523 String extractedPropertiesOrFieldsDescription = extractedDescriptionOf(propertiesOrFields);524 String description = mostRelevantDescription(info.description(), extractedPropertiesOrFieldsDescription);525 return new ObjectArrayAssert<>(values.toArray()).as(description);526 }527 /**528 * Assert that the object under test (actual) is equal to the given object based on recursive a property/field by property/field comparison (including529 * inherited ones). This can be useful if actual's {@code equals} implementation does not suit you.530 * The recursive property/field comparison is <b>not</b> applied on fields having a custom {@code equals} implementation, i.e.531 * the overridden {@code equals} method will be used instead of a field by field comparison.532 * <p>533 * The recursive comparison handles cycles. By default {@code floats} are compared with a precision of 1.0E-6 and {@code doubles} with 1.0E-15.534 * <p>535 * You can specify a custom comparator per (nested) fields or type with respectively {@link #usingComparatorForFields(Comparator, String...) usingComparatorForFields(Comparator, String...)}536 * and {@link #usingComparatorForType(Comparator, Class)}.537 * <p>538 * The objects to compare can be of different types but must have the same properties/fields. For example if actual object has a name String field, it is expected the other object to also have one.539 * If an object has a field and a property with the same name, the property value will be used over the field.540 * <p>541 * Example:542 * <pre><code class='java'> public class Person {543 * public String name;544 * public double height;545 * public Home home = new Home();546 * public Person bestFriend;547 * // constructor with name and height omitted for brevity548 * }549 *550 * public class Home {551 * public Address address = new Address();552 * }553 *554 * public static class Address {555 * public int number = 1;556 * }557 *558 * Person jack = new Person("Jack", 1.80);559 * jack.home.address.number = 123;560 *561 * Person jackClone = new Person("Jack", 1.80);562 * jackClone.home.address.number = 123;563 *564 * // cycle are handled in comparison565 * jack.bestFriend = jackClone;566 * jackClone.bestFriend = jack;567 *568 * // will fail as equals compares object references569 * assertThat(jack).isEqualsTo(jackClone);570 *571 * // jack and jackClone are equals when doing a recursive field by field comparison572 * assertThat(jack).isEqualToComparingFieldByFieldRecursively(jackClone);573 *574 * // any type/field can be compared with a a specific comparator.575 * // let's change jack's height a little bit576 * jack.height = 1.81;577 *578 * // assertion fails because of the height difference579 * // (the default precision comparison for double is 1.0E-15)580 * assertThat(jack).isEqualToComparingFieldByFieldRecursively(jackClone);581 *582 * // this succeeds because we allow a 0.5 tolerance on double583 * assertThat(jack).usingComparatorForType(new DoubleComparator(0.5), Double.class)584 * .isEqualToComparingFieldByFieldRecursively(jackClone);585 *586 * // you can set a comparator on specific fields (nested fields are supported)587 * assertThat(jack).usingComparatorForFields(new DoubleComparator(0.5), "height")588 * .isEqualToComparingFieldByFieldRecursively(jackClone);</code></pre>589 *590 * @param other the object to compare {@code actual} to.591 * @return {@code this} assertion object.592 * @throws AssertionError if the actual object is {@code null}.593 * @throws AssertionError if the actual and the given objects are not deeply equal property/field by property/field.594 * @throws IntrospectionError if one property/field to compare can not be found.595 */596 public SELF isEqualToComparingFieldByFieldRecursively(Object other) {597 objects.assertIsEqualToComparingFieldByFieldRecursively(info, actual, other, comparatorByPropertyOrField,598 comparatorByType);599 return myself;600 }601}...
Source:AbstractBuildpathQuickFixProcessorTest.java
...307 problem = Stream.of(cu.getProblems())308 // Find problems that contain the "hover point"309 .filter(problem -> (problem.getSourceEnd() >= offset && problem.getSourceStart() <= (offset + length)))310 // Find the smallest311 .min((a, b) -> Integer.compare(a.getSourceEnd() - a.getSourceStart(),312 b.getSourceEnd() - b.getSourceStart()))313 .orElseThrow(() -> new IllegalArgumentException(314 "No problems found after filtering: " + Stream.of(cu.getProblems())315 .map(this::toString)316 .collect(Collectors.joining(","))));317 locs = new IProblemLocation[] {318 new ProblemLocation(problem)319 };320 } catch (Exception e) {321 throw Exceptions.duck(e);322 }323 }324 /**325 * Workhorse method for driving the quick fix processor and getting the...
compare
Using AI Code Generation
1import static org.assertj.core.api.Assertions.assertThat;2public class Test {3 public static void main(String[] args) {4 String[] actual = {"a", "b", "c"};5 String[] expected = {"a", "b", "c"};6 assertThat(actual).containsExactlyInAnyOrder(expected);7 }8}9to contain exactly (and in same order):10to contain exactly (and in same order):
compare
Using AI Code Generation
1public class AssertJCompareMethodExample {2 public static void main(String[] args) {3 String[] actual = new String[]{"a", "b", "c"};4 String[] expected = new String[]{"a", "b", "c"};5 Assertions.assertThat(actual).usingElementComparator(String::compareTo).containsExactly(expected);6 }7}8Related Posts: AssertJ - usingElementComparator() method9AssertJ - usingComparatorForFields() method10AssertJ - usingComparatorForType() method11AssertJ - usingComparator() method12AssertJ - usingRecursiveComparison() method13AssertJ - usingDefaultComparator() method
compare
Using AI Code Generation
1import static org.assertj.core.api.Assertions.assertThat;2import org.assertj.core.api.AbstractObjectArrayAssert;3import org.assertj.core.api.ObjectArrayAssert;4public class ObjectArrayAssert_compare {5 public static void main(String[] args) {6 Object[] objArr = {"abc", "def", "ghi"};7 ObjectArrayAssert<Object> objArrAssert = assertThat(objArr);8 AbstractObjectArrayAssert<?, Object[]> abstractObjArrAssert = objArrAssert.compare();9 abstractObjArrAssert.isEqualTo(objArr);10 }11}
compare
Using AI Code Generation
1public class AssertjObjectArrayAssertCompareMethodExample {2 public static void main(String[] args) {3 Object[] array1 = new Object[]{"a", "b", "c"};4 Object[] array2 = new Object[]{"a", "b", "c"};5 Object[] array3 = new Object[]{"a", "b"};6 Object[] array4 = new Object[]{"a", "b", "d"};7 Object[] array5 = new Object[]{"a", "b", "c", "d"};8 Object[] array6 = new Object[]{"a", "b", "c"};9 Object[] array7 = new Object[]{"a", "b", "c", "d"};10 Object[] array8 = new Object[]{"a", "b", "c", "d"};11 Object[] array9 = new Object[]{"a", "b", "c", "d"};12 Object[] array10 = new Object[]{"a", "b", "c", "d"};13 Object[] array11 = new Object[]{"a", "b", "c", "d"};14 Object[] array12 = new Object[]{"a", "b", "c", "d"};15 Object[] array13 = new Object[]{"a", "b", "c", "d"};16 Object[] array14 = new Object[]{"a", "b", "c", "d"};17 Object[] array15 = new Object[]{"a", "b", "c", "d"};18 Object[] array16 = new Object[]{"a", "b", "c", "d"};19 Object[] array17 = new Object[]{"a", "b", "c", "d"};20 Object[] array18 = new Object[]{"a", "b", "c", "d"};21 Object[] array19 = new Object[]{"a", "b", "c", "d"};22 Object[] array20 = new Object[]{"a", "b", "c", "d"};23 Object[] array21 = new Object[]{"a", "b", "c", "d"};24 Object[] array22 = new Object[]{"a", "b", "c", "d"};25 Object[] array23 = new Object[]{"a", "b", "c", "d"};26 Object[] array24 = new Object[]{"a", "b", "c", "d"};27 Object[] array25 = new Object[]{"a", "b", "
compare
Using AI Code Generation
1import org.assertj.core.api.Assertions;2import org.assertj.core.api.AbstractAssert;3import org.assertj.core.api.AbstractObjectArrayAssert;4import org.assertj.core.api.AbstractCharSequenceAssert;5public class Test {6 public static void main(String[] args) {7 String[] array = {"A", "B", "C"};8 AbstractObjectArrayAssert<?, String[]> assert1 = Assertions.assertThat(array);9 AbstractObjectArrayAssert<?, String[]> assert2 = Assertions.assertThat(array);10 assert1.isEqualTo(array);11 assert2.isEqualTo(array);12 assert1.isEqualTo(assert2);13 }14}15at org.assertj.core.api.AbstractObjectArrayAssert.isEqualTo(AbstractObjectArrayAssert.java:71)16at org.assertj.core.api.AbstractObjectArrayAssert.isEqualTo(AbstractObjectArrayAssert.java:30)17at Test.main(Test.java:13)18public SELF isEqualTo(Object obj) {19 if (obj == null) throw new NullPointerException("Expecting actual not to be null");20 if (actual == obj) return myself;21 if (actual == null || obj == null || !actual.getClass().isArray() || !obj.getClass().isArray()) {22 throw failures.failure(info, shouldBeEqual(actual, obj));23 }24 if (actual.getClass() != obj.getClass()) {25 throw failures.failure(info, shouldBeEqual(actual, obj));26 }27 if (actual instanceof Object[] && obj instanceof Object[]) {28 objects.assertEqual(info, (Object[]) actual, (Object[]) obj);29 } else if (actual instanceof boolean[] && obj instanceof boolean[]) {30 booleans.assertEqual(info, (boolean[]) actual, (boolean[]) obj);31 } else if (actual instanceof byte[] && obj instanceof byte[]) {32 bytes.assertEqual(info, (byte[]) actual, (byte[]) obj);33 } else if (actual instanceof char[] && obj instanceof char[]) {34 chars.assertEqual(info, (char[]) actual, (char[]) obj);35 } else if (actual instanceof double[] && obj instanceof double[]) {36 doubles.assertEqual(info, (double[]) actual, (double[]) obj);37 } else if (actual instanceof float[] && obj instanceof float[]) {
compare
Using AI Code Generation
1import static org.assertj.core.api.Assertions.assertThat;2import java.util.ArrayList;3import java.util.List;4import java.util.Arrays;5import org.junit.Test;6{7 public void test()8 {9 List<String> list1 = new ArrayList<>(Arrays.asList("a", "b", "c"));10 List<String> list2 = new ArrayList<>(Arrays.asList("a", "b", "c"));11 assertThat(list1).containsExactlyElementsOf(list2);12 }13}14to contain exactly (and in same order):15at org.assertj.core.api.AbstractObjectArrayAssert.containsExactly(AbstractObjectArrayAssert.java:156)16at org.assertj.core.api.AbstractObjectArrayAssert.containsExactlyElementsOf(AbstractObjectArrayAssert.java:147)17at Test1.test(Test1.java:11)18at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)19at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)20at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)21at java.base/java.lang.reflect.Method.invoke(Method.java:566)22at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)23at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)24at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)25at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)26at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)27at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)28at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)29at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
compare
Using AI Code Generation
1import org.assertj.core.api.Assertions;2import org.junit.Test;3public class AssertJCompareMethod {4 public void test() {5 String[] expected = {"a", "b", "c"};6 String[] actual = {"a", "b", "c"};7 Assertions.assertThat(actual).as("test").usingComparatorForType((s1, s2) -> s1.compareTo(s2), String.class).isEqualTo(expected);8 }9}
compare
Using AI Code Generation
1import org.assertj.core.api.Assertions;2import org.testng.annotations.Test;3public class Test1 {4public void test1() {5String[] stringArray = {"A", "B", "C"};6Assertions.assertThat(stringArray).contains("A");7}8}9Method test1() should not have parameters10 at org.testng.internal.MethodHelper.validateNoParameters(MethodHelper.java:45)11 at org.testng.internal.MethodInvoker.invokeMethod(MethodInvoker.java:136)12 at org.testng.internal.MethodInvoker.invokeTestMethod(MethodInvoker.java:175)13 at org.testng.internal.MethodInvoker.invokeTestMethods(MethodInvoker.java:147)14 at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:146)15 at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:125)16 at org.testng.TestRunner.privateRun(TestRunner.java:785)17 at org.testng.TestRunner.run(TestRunner.java:635)18 at org.testng.SuiteRunner.runTest(SuiteRunner.java:387)19 at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:382)20 at org.testng.SuiteRunner.privateRun(SuiteRunner.java:340)21 at org.testng.SuiteRunner.run(SuiteRunner.java:289)22 at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:53)23 at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:96)24 at org.testng.TestNG.runSuitesSequentially(TestNG.java:1293)25 at org.testng.TestNG.runSuitesLocally(TestNG.java:1218)26 at org.testng.TestNG.runSuites(TestNG.java:1133)27 at org.testng.TestNG.run(TestNG.java:1104)28 at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:132)29 at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:253)30 at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)
compare
Using AI Code Generation
1import org.assertj.core.api.AbstractObjectArrayAssert;2public class AssertJCompare {3public static void main(String[] args) {4Object[] array1 = {1, 2, 3};5Object[] array2 = {1, 2, 3};6AbstractObjectArrayAssert<?, ?> objectArrayAssert = new AbstractObjectArrayAssert<Object[]>(array1, AbstractObjectArrayAssert.class) {};7objectArrayAssert.isEqualTo(array2);8}9}10at org.assertj.core.api.AbstractObjectArrayAssert.isEqualTo(AbstractObjectArrayAssert.java:101)11at org.assertj.core.api.AbstractObjectArrayAssert.isEqualTo(AbstractObjectArrayAssert.java:45)12at AssertJCompare.main(AssertJCompare.java:15)
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!