Best Assertj code snippet using org.assertj.core.api.recursive.comparison.RecursiveComparisonConfiguration.describeRegisteredErrorMessagesForFields
Source:RecursiveComparisonConfiguration.java
...566 describeIgnoredCollectionOrderInFieldsMatchingRegexes(description);567 describeRegisteredComparatorByTypes(description);568 describeRegisteredComparatorForFields(description);569 describeTypeCheckingStrictness(description);570 describeRegisteredErrorMessagesForFields(description);571 describeRegisteredErrorMessagesForTypes(description);572 return description.toString();573 }574 boolean shouldIgnore(DualValue dualValue) {575 return shouldIgnoreFieldBasedOnFieldLocation(dualValue.fieldLocation) || shouldIgnoreFieldBasedOnFieldValue(dualValue);576 }577 private boolean shouldBeCompared(FieldLocation fieldLocation) {578 // empty comparedFields <=> no restriction on compared fields <=> must be compared579 if (comparedFields.isEmpty()) return true;580 return comparedFields.stream().anyMatch(matchesComparedField(fieldLocation));581 }582 private static Predicate<FieldLocation> matchesComparedField(FieldLocation field) {583 // a field f must be compared if any compared fields is f itself (obviously), a parent of f or a child of f.584 // - "name.first" must be compared if "name" is a compared field so will other "name" subfields like "name.last"585 // - "name" must be compared if "name.first" is a compared field otherwise "name" is ignored and "name.first" too586 return comparedField -> field.matches(comparedField) // exact match587 || field.hasParent(comparedField) // ex: field "name.first" and "name" compared field588 || field.hasChild(comparedField); // ex: field "name" and "name.first" compared field589 }590 Set<String> getActualFieldNamesToCompare(DualValue dualValue) {591 Set<String> actualFieldsNames = Objects.getFieldsNames(dualValue.actual.getClass());592 // we are doing the same as shouldIgnore(DualValue dualValue) but in two steps for performance reasons:593 // - we filter first ignored field by names that don't need building DualValues594 // - then we filter field DualValues with the remaining criteria that need to get the field value595 // DualValues are built introspecting fields which is expensive.596 return actualFieldsNames.stream()597 // evaluate field name ignoring criteria on dualValue field location + field name598 .filter(fieldName -> !shouldIgnoreFieldBasedOnFieldLocation(dualValue.fieldLocation.field(fieldName)))599 .map(fieldName -> dualValueForField(dualValue, fieldName))600 // evaluate field value ignoring criteria601 .filter(fieldDualValue -> !shouldIgnoreFieldBasedOnFieldValue(fieldDualValue))602 // back to field name603 .map(DualValue::getFieldName)604 .filter(fieldName -> !fieldName.isEmpty())605 .collect(toSet());606 }607 // non accessible stuff608 private boolean shouldIgnoreFieldBasedOnFieldValue(DualValue dualValue) {609 return matchesAnIgnoredNullField(dualValue)610 || matchesAnIgnoredFieldType(dualValue)611 || matchesAnIgnoredEmptyOptionalField(dualValue);612 }613 private boolean shouldIgnoreFieldBasedOnFieldLocation(FieldLocation fieldLocation) {614 return !shouldBeCompared(fieldLocation) || matchesAnIgnoredField(fieldLocation) || matchesAnIgnoredFieldRegex(fieldLocation);615 }616 private static DualValue dualValueForField(DualValue parentDualValue, String fieldName) {617 Object actualFieldValue = COMPARISON.getSimpleValue(fieldName, parentDualValue.actual);618 // no guarantees we have a field in expected named as fieldName619 Object expectedFieldValue;620 try {621 expectedFieldValue = COMPARISON.getSimpleValue(fieldName, parentDualValue.expected);622 } catch (@SuppressWarnings("unused") Exception e) {623 // set the field to null to express it is absent, this not 100% accurate as the value could be null624 // but it works to evaluate if dualValue should be ignored with matchesAnIgnoredFieldType625 expectedFieldValue = null;626 }627 FieldLocation fieldLocation = parentDualValue.fieldLocation.field(fieldName);628 return new DualValue(fieldLocation, actualFieldValue, expectedFieldValue);629 }630 boolean hasCustomComparator(DualValue dualValue) {631 String fieldName = dualValue.getConcatenatedPath();632 if (hasComparatorForField(fieldName)) return true;633 if (dualValue.actual == null && dualValue.expected == null) return false;634 // best effort assuming actual and expected have the same type (not 100% true as we can compare object of different types)635 Class<?> valueType = dualValue.actual != null ? dualValue.actual.getClass() : dualValue.expected.getClass();636 return hasComparatorForType(valueType);637 }638 boolean shouldIgnoreOverriddenEqualsOf(DualValue dualValue) {639 // we must compare java basic types otherwise the recursive comparison loops infinitely!640 if (dualValue.isActualJavaType()) return false;641 // enums don't have fields, comparing them field by field makes no sense, we need to use equals which is overridden and final642 if (dualValue.isActualAnEnum()) return false;643 return ignoreAllOverriddenEquals644 || matchesAnIgnoredOverriddenEqualsField(dualValue.fieldLocation)645 || (dualValue.actual != null && shouldIgnoreOverriddenEqualsOf(dualValue.actual.getClass()));646 }647 @VisibleForTesting648 boolean shouldIgnoreOverriddenEqualsOf(Class<?> clazz) {649 return matchesAnIgnoredOverriddenEqualsRegex(clazz) || matchesAnIgnoredOverriddenEqualsType(clazz);650 }651 boolean shouldIgnoreCollectionOrder(FieldLocation fieldLocation) {652 return ignoreCollectionOrder653 || matchesAnIgnoredCollectionOrderInField(fieldLocation)654 || matchesAnIgnoredCollectionOrderInFieldRegex(fieldLocation);655 }656 private void describeIgnoredFieldsRegexes(StringBuilder description) {657 if (!ignoredFieldsRegexes.isEmpty())658 description.append(format("- the fields matching the following regexes were ignored in the comparison: %s%n",659 describeRegexes(ignoredFieldsRegexes)));660 }661 private void describeIgnoredFields(StringBuilder description) {662 if (!ignoredFields.isEmpty())663 description.append(format("- the following fields were ignored in the comparison: %s%n", describeIgnoredFields()));664 }665 private void describeComparedFields(StringBuilder description) {666 if (!comparedFields.isEmpty())667 description.append(format("- the comparison was performed on the following fields: %s%n", describeComparedFields()));668 }669 private void describeIgnoredFieldsForTypes(StringBuilder description) {670 if (!ignoredTypes.isEmpty())671 description.append(format("- the following types were ignored in the comparison: %s%n", describeIgnoredTypes()));672 }673 private void describeIgnoreAllActualNullFields(StringBuilder description) {674 if (ignoreAllActualNullFields) description.append(format("- all actual null fields were ignored in the comparison%n"));675 }676 private void describeIgnoreAllActualEmptyOptionalFields(StringBuilder description) {677 if (getIgnoreAllActualEmptyOptionalFields())678 description.append(format("- all actual empty optional fields were ignored in the comparison (including Optional, OptionalInt, OptionalLong and OptionalDouble)%n"));679 }680 private void describeIgnoreAllExpectedNullFields(StringBuilder description) {681 if (ignoreAllExpectedNullFields) description.append(format("- all expected null fields were ignored in the comparison%n"));682 }683 private void describeOverriddenEqualsMethodsUsage(StringBuilder description, Representation representation) {684 String header = ignoreAllOverriddenEquals685 ? "- no overridden equals methods were used in the comparison (except for java types)"686 : "- overridden equals methods were used in the comparison";687 description.append(header);688 if (isConfiguredToIgnoreSomeButNotAllOverriddenEqualsMethods()) {689 description.append(format(" except for:%n"));690 describeIgnoredOverriddenEqualsMethods(description, representation);691 } else {692 description.append(format("%n"));693 }694 }695 private void describeIgnoredOverriddenEqualsMethods(StringBuilder description, Representation representation) {696 if (!ignoredOverriddenEqualsForFields.isEmpty())697 description.append(format("%s the following fields: %s%n", INDENT_LEVEL_2,698 describeIgnoredOverriddenEqualsForFields()));699 if (!ignoredOverriddenEqualsForTypes.isEmpty())700 description.append(format("%s the following types: %s%n", INDENT_LEVEL_2,701 describeIgnoredOverriddenEqualsForTypes(representation)));702 if (!ignoredOverriddenEqualsForFieldsMatchingRegexes.isEmpty())703 description.append(format("%s the types matching the following regexes: %s%n", INDENT_LEVEL_2,704 describeRegexes(ignoredOverriddenEqualsForFieldsMatchingRegexes)));705 }706 private String describeIgnoredOverriddenEqualsForTypes(Representation representation) {707 List<String> fieldsDescription = ignoredOverriddenEqualsForTypes.stream()708 .map(representation::toStringOf)709 .collect(toList());710 return join(fieldsDescription);711 }712 private String describeIgnoredOverriddenEqualsForFields() {713 return join(ignoredOverriddenEqualsForFields);714 }715 private void describeIgnoreCollectionOrder(StringBuilder description) {716 if (ignoreCollectionOrder) description.append(format("- collection order was ignored in all fields in the comparison%n"));717 }718 private void describeIgnoredCollectionOrderInFields(StringBuilder description) {719 if (!ignoredCollectionOrderInFields.isEmpty())720 description.append(format("- collection order was ignored in the following fields in the comparison: %s%n",721 describeIgnoredCollectionOrderInFields()));722 }723 private void describeIgnoredCollectionOrderInFieldsMatchingRegexes(StringBuilder description) {724 if (!ignoredCollectionOrderInFieldsMatchingRegexes.isEmpty())725 description.append(format("- collection order was ignored in the fields matching the following regexes in the comparison: %s%n",726 describeRegexes(ignoredCollectionOrderInFieldsMatchingRegexes)));727 }728 private boolean matchesAnIgnoredOverriddenEqualsRegex(Class<?> clazz) {729 if (ignoredOverriddenEqualsForFieldsMatchingRegexes.isEmpty()) return false; // shortcut730 String canonicalName = clazz.getCanonicalName();731 return ignoredOverriddenEqualsForFieldsMatchingRegexes.stream().anyMatch(regex -> regex.matcher(canonicalName).matches());732 }733 private boolean matchesAnIgnoredOverriddenEqualsType(Class<?> clazz) {734 return ignoredOverriddenEqualsForTypes.contains(clazz);735 }736 private boolean matchesAnIgnoredOverriddenEqualsField(FieldLocation fieldLocation) {737 return ignoredOverriddenEqualsForFields.stream().anyMatch(fieldLocation::matches);738 }739 private boolean matchesAnIgnoredNullField(DualValue dualValue) {740 return (ignoreAllActualNullFields && dualValue.actual == null)741 || (ignoreAllExpectedNullFields && dualValue.expected == null);742 }743 private boolean matchesAnIgnoredEmptyOptionalField(DualValue dualValue) {744 return ignoreAllActualEmptyOptionalFields745 && dualValue.isActualFieldAnEmptyOptionalOfAnyType();746 }747 private boolean matchesAnIgnoredFieldRegex(FieldLocation fieldLocation) {748 return ignoredFieldsRegexes.stream()749 .anyMatch(regex -> regex.matcher(fieldLocation.getPathToUseInRules()).matches());750 }751 private boolean matchesAnIgnoredFieldType(DualValue dualValue) {752 Object actual = dualValue.actual;753 if (actual != null) return ignoredTypes.contains(actual.getClass());754 Object expected = dualValue.expected;755 // actual is null => we can't evaluate its type, we can only reliably check dualValue.expected's type if756 // strictTypeChecking is enabled which guarantees expected is of the same type.757 if (strictTypeChecking && expected != null) return ignoredTypes.contains(expected.getClass());758 // if strictTypeChecking is disabled, we can't safely ignore the field (if we did, we would ignore all null fields!).759 return false;760 }761 private boolean matchesAnIgnoredField(FieldLocation fieldLocation) {762 return ignoredFields.stream().anyMatch(fieldLocation::matches);763 }764 private boolean matchesAnIgnoredCollectionOrderInField(FieldLocation fieldLocation) {765 return ignoredCollectionOrderInFields.stream().anyMatch(fieldLocation::matches);766 }767 private boolean matchesAnIgnoredCollectionOrderInFieldRegex(FieldLocation fieldLocation) {768 String pathToUseInRules = fieldLocation.getPathToUseInRules();769 return ignoredCollectionOrderInFieldsMatchingRegexes.stream().anyMatch(regex -> regex.matcher(pathToUseInRules).matches());770 }771 private String describeIgnoredFields() {772 return join(ignoredFields);773 }774 private String describeComparedFields() {775 return join(comparedFields.stream().map(FieldLocation::shortDescription).collect(toList()));776 }777 private String describeIgnoredTypes() {778 List<String> typesDescription = ignoredTypes.stream()779 .map(Class::getName)780 .collect(toList());781 return join(typesDescription);782 }783 private static String join(Collection<String> typesDescription) {784 return Strings.join(typesDescription).with(DEFAULT_DELIMITER);785 }786 private String describeIgnoredCollectionOrderInFields() {787 return join(ignoredCollectionOrderInFields);788 }789 private String describeRegexes(List<Pattern> regexes) {790 List<String> fieldsDescription = regexes.stream()791 .map(Pattern::pattern)792 .collect(toList());793 return join(fieldsDescription);794 }795 private boolean isConfiguredToIgnoreSomeButNotAllOverriddenEqualsMethods() {796 boolean ignoreSomeOverriddenEqualsMethods = !ignoredOverriddenEqualsForFieldsMatchingRegexes.isEmpty()797 || !ignoredOverriddenEqualsForTypes.isEmpty()798 || !ignoredOverriddenEqualsForFields.isEmpty();799 return !ignoreAllOverriddenEquals && ignoreSomeOverriddenEqualsMethods;800 }801 private void describeRegisteredComparatorByTypes(StringBuilder description) {802 if (!typeComparators.isEmpty()) {803 description.append(format("- these types were compared with the following comparators:%n"));804 describeComparatorForTypes(description);805 }806 }807 private void describeComparatorForTypes(StringBuilder description) {808 typeComparators.comparatorByTypes()809 .map(this::formatRegisteredComparatorByType)810 .forEach(description::append);811 }812 private String formatRegisteredComparatorByType(Entry<Class<?>, Comparator<?>> next) {813 return format("%s %s -> %s%n", INDENT_LEVEL_2, next.getKey().getName(), next.getValue());814 }815 private void describeRegisteredComparatorForFields(StringBuilder description) {816 if (!fieldComparators.isEmpty()) {817 description.append(format("- these fields were compared with the following comparators:%n"));818 describeComparatorForFields(description);819 if (!typeComparators.isEmpty()) {820 description.append(format("- field comparators take precedence over type comparators.%n"));821 }822 }823 }824 private void describeComparatorForFields(StringBuilder description) {825 fieldComparators.comparatorByFields()826 .map(this::formatRegisteredComparatorForField)827 .forEach(description::append);828 }829 private String formatRegisteredComparatorForField(Entry<String, Comparator<?>> comparatorForField) {830 return format("%s %s -> %s%n", INDENT_LEVEL_2, comparatorForField.getKey(), comparatorForField.getValue());831 }832 private void describeTypeCheckingStrictness(StringBuilder description) {833 String str = strictTypeChecking834 ? "- actual and expected objects and their fields were considered different when of incompatible types (i.e. expected type does not extend actual's type) even if all their fields match, for example a Person instance will never match a PersonDto (call strictTypeChecking(false) to change that behavior).%n"835 : "- actual and expected objects and their fields were compared field by field recursively even if they were not of the same type, this allows for example to compare a Person to a PersonDto (call strictTypeChecking(true) to change that behavior).%n";836 description.append(format(str));837 }838 private void describeRegisteredErrorMessagesForFields(StringBuilder description) {839 if (!fieldMessages.isEmpty()) {840 description.append(format("- these fields had overridden error messages:%n"));841 describeErrorMessagesForFields(description);842 if (!typeMessages.isEmpty()) {843 description.append(format("- field custom messages take precedence over type messages.%n"));844 }845 }846 }847 private void describeErrorMessagesForFields(StringBuilder description) {848 String fields = fieldMessages.messageByFields()849 .map(Entry::getKey)850 .collect(joining(DEFAULT_DELIMITER));851 description.append(format("%s %s%n", INDENT_LEVEL_2, fields));852 }...
describeRegisteredErrorMessagesForFields
Using AI Code Generation
1import org.assertj.core.api.recursive.comparison.RecursiveComparisonConfiguration;2import org.assertj.core.api.recursive.comparison.RecursiveComparisonDifference;3import java.util.List;4import static org.assertj.core.api.Assertions.assertThat;5public class RecursiveComparisonConfigurationTest {6 public static void main(String[] args) {7 Person person1 = new Person("John", "Doe");8 Person person2 = new Person("John", "Doe");9 new RecursiveComparisonConfiguration().withIgnoredFields("firstName");10 recursiveComparisonConfiguration.getRecursiveComparisonDifferenceList(person1, person2);11 assertThat(differences).isEmpty();12 System.out.println(recursiveComparisonConfiguration.describeRegisteredErrorMessagesForFields());13 }14}15class Person {16 String firstName;17 String lastName;18 public Person(String firstName, String lastName) {19 this.firstName = firstName;20 this.lastName = lastName;21 }22 public String getFirstName() {23 return firstName;24 }25 public String getLastName() {26 return lastName;27 }28}
describeRegisteredErrorMessagesForFields
Using AI Code Generation
1import org.assertj.core.api.recursive.comparison.RecursiveComparisonConfiguration;2import org.assertj.core.api.recursive.comparison.RegisteredFieldOrPropertyExtractor;3import java.util.Arrays;4import java.util.List;5public class RecursiveComparisonConfigurationTest {6 public static void main(String[] args) {7 RecursiveComparisonConfiguration recursiveComparisonConfiguration = new RecursiveComparisonConfiguration();8 RegisteredFieldOrPropertyExtractor registeredFieldOrPropertyExtractor = new RegisteredFieldOrPropertyExtractor();9 recursiveComparisonConfiguration.registerFieldOrPropertyExtractor(registeredFieldOrPropertyExtractor);10 System.out.println(recursiveComparisonConfiguration.describeRegisteredErrorMessagesForFields());11 }12}
describeRegisteredErrorMessagesForFields
Using AI Code Generation
1import static org.assertj.core.api.Assertions.*;2import static org.assertj.core.api.recursive.comparison.RecursiveComparisonConfiguration.*;3public class RecursiveComparisonConfigurationExample {4 public void should_describe_registered_error_messages() {5 String expected = "John";6 String actual = "Paul";7 RecursiveComparisonConfiguration configuration = recursiveComparison()8 .registerExpectedValue(expected)9 .registerActualValue(actual);10 String description = configuration.describeRegisteredErrorMessagesForFields();11 assertThat(description).isEqualTo(""12");13 }14}15import static org.assertj.core.api.Assertions.*;16import static org.assertj.core.api.recursive.comparison.RecursiveComparisonConfiguration.*;17import java.util.ArrayList;18import java.util.List;19import org.junit.jupiter.api.Test;20public class RecursiveComparisonConfigurationExample {21 public void should_use_recursive_comparison_configuration() {22 Person expected = new Person("John", 42);23 Person actual = new Person("Paul", 42);24 assertThat(actual).usingRecursiveComparison()25 .isEqualTo(expected);26 }27 private static class Person {28 private final String name;29 private final int age;30 private final List<Person> children = new ArrayList<>();31 private Person(String name, int age) {32 this.name = name;33 this.age = age;34 }35 public String getName() {36 return name;37 }38 public int getAge() {39 return age;40 }41 public List<Person> getChildren() {42 return children;43 }44 }45}46 Person(name=Paul, age=42
describeRegisteredErrorMessagesForFields
Using AI Code Generation
1org.assertj.core.api.recursive.comparison.RecursiveComparisonConfiguration describeRegisteredErrorMessagesForFields(java.util.List<java.lang.String> fields, java.lang.String description)2org.assertj.core.api.recursive.comparison.RecursiveComparisonConfiguration describeRegisteredErrorMessagesForFields(java.lang.String field, java.lang.String description)3org.assertj.core.api.recursive.comparison.RecursiveComparisonConfiguration describeRegisteredErrorMessagesForFieldsMatching(java.util.regex.Pattern fieldsPattern, java.lang.String description)4org.assertj.core.api.recursive.comparison.RecursiveComparisonConfiguration describeRegisteredErrorMessagesForFieldsMatching(java.lang.String fieldsPattern, java.lang.String description)5org.assertj.core.api.recursive.comparison.RecursiveComparisonConfiguration describeRegisteredErrorMessagesForFieldsMatching(java.util.regex.Pattern fieldsPattern, java.util.function.Function<java.lang.String,java.lang.String> descriptionFunction)6org.assertj.core.api.recursive.comparison.RecursiveComparisonConfiguration describeRegisteredErrorMessagesForFieldsMatching(java.lang.String fieldsPattern, java.util.function.Function<java.lang.String,java.lang.String> descriptionFunction)7org.assertj.core.api.recursive.comparison.RecursiveComparisonConfiguration ignoreAllActualNullFields()8org.assertj.core.api.recursive.comparison.RecursiveComparisonConfiguration ignoreAllExpectedNullFields()9org.assertj.core.api.recursive.comparison.RecursiveComparisonConfiguration ignoreAllOverriddenEqualsForFields(java.util.List<java.lang.String> fields)10org.assertj.core.api.recursive.comparison.RecursiveComparisonConfiguration ignoreAllOverriddenEqualsForFields(java.lang.String field)11org.assertj.core.api.recursive.comparison.RecursiveComparisonConfiguration ignoreAllOverriddenEqualsForFieldsMatching(java.util.regex.Pattern fieldsPattern)12org.assertj.core.api.recursive.comparison.RecursiveComparisonConfiguration ignoreAllOverriddenEqualsForFieldsMatching(java.lang.String fieldsPattern)13org.assertj.core.api.recursive.comparison.RecursiveComparisonConfiguration ignoreAllOverriddenEquals()14org.assertj.core.api.recursive.comparison.RecursiveComparisonConfiguration ignoreAllOverriddenEquals(java.util.List<java.lang.String> fields)15org.assertj.core.api.recursive.comparison.RecursiveComparisonConfiguration ignoreAllOverriddenEquals(java.lang.String field)16org.assertj.core.api.recursive.comparison.RecursiveComparisonConfiguration ignoreAllOverriddenEqualsMatching(java.util.regex.Pattern fieldsPattern)17org.assertj.core.api.recursive.comparison.RecursiveComparisonConfiguration ignoreAllOverriddenEqualsMatching(java.lang.String fieldsPattern)
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!!