How to use FieldMessages method of org.assertj.core.api.recursive.comparison.RecursiveComparisonConfiguration class

Best Assertj code snippet using org.assertj.core.api.recursive.comparison.RecursiveComparisonConfiguration.FieldMessages

Source:RecursiveComparisonConfiguration.java Github

copy

Full Screen

...67 private TypeComparators typeComparators = defaultTypeComparators();68 private FieldComparators fieldComparators = new FieldComparators();69 // registered messages section70 private TypeMessages typeMessages = new TypeMessages();71 private FieldMessages fieldMessages = new FieldMessages();72 private RecursiveComparisonConfiguration(Builder builder) {73 this.strictTypeChecking = builder.strictTypeChecking;74 this.ignoreAllActualNullFields = builder.ignoreAllActualNullFields;75 this.ignoreAllActualEmptyOptionalFields = builder.ignoreAllActualEmptyOptionalFields;76 this.ignoreAllExpectedNullFields = builder.ignoreAllExpectedNullFields;77 this.ignoredFields = newLinkedHashSet(builder.ignoredFields);78 this.comparedFields = newLinkedHashSet(builder.comparedFields);79 ignoreFieldsMatchingRegexes(builder.ignoredFieldsMatchingRegexes);80 ignoreFieldsOfTypes(builder.ignoredTypes);81 ignoreOverriddenEqualsForTypes(builder.ignoredOverriddenEqualsForTypes);82 this.ignoredOverriddenEqualsForFields = list(builder.ignoredOverriddenEqualsForFields);83 ignoreOverriddenEqualsForFieldsMatchingRegexes(builder.ignoredOverriddenEqualsForFieldsMatchingRegexes);84 this.ignoreAllOverriddenEquals = builder.ignoreAllOverriddenEquals;85 this.ignoreCollectionOrder = builder.ignoreCollectionOrder;86 this.ignoredCollectionOrderInFields = newLinkedHashSet(builder.ignoredCollectionOrderInFields);87 ignoreCollectionOrderInFieldsMatchingRegexes(builder.ignoredCollectionOrderInFieldsMatchingRegexes);88 this.typeComparators = builder.typeComparators;89 this.fieldComparators = builder.fieldComparators;90 this.fieldMessages = builder.fieldMessages;91 this.typeMessages = builder.typeMessages;92 }93 public RecursiveComparisonConfiguration() {}94 public boolean hasComparatorForField(String fieldName) {95 return fieldComparators.hasComparatorForField(fieldName);96 }97 public Comparator<?> getComparatorForField(String fieldName) {98 return fieldComparators.getComparatorForField(fieldName);99 }100 public boolean hasCustomMessageForField(String fieldName) {101 return fieldMessages.hasMessageForField(fieldName);102 }103 public String getMessageForField(String fieldName) {104 return fieldMessages.getMessageForField(fieldName);105 }106 public FieldComparators getFieldComparators() {107 return fieldComparators;108 }109 public boolean hasComparatorForType(Class<?> keyType) {110 return typeComparators.hasComparatorForType(keyType);111 }112 public boolean hasCustomComparators() {113 return !typeComparators.isEmpty() || !fieldComparators.isEmpty();114 }115 public Comparator<?> getComparatorForType(Class<?> fieldType) {116 return typeComparators.getComparatorForType(fieldType);117 }118 public boolean hasCustomMessageForType(Class<?> fieldType) {119 return typeMessages.hasMessageForType(fieldType);120 }121 public String getMessageForType(Class<?> fieldType) {122 return typeMessages.getMessageForType(fieldType);123 }124 public TypeComparators getTypeComparators() {125 return typeComparators;126 }127 Stream<Entry<Class<?>, Comparator<?>>> comparatorByTypes() {128 return typeComparators.comparatorByTypes();129 }130 @VisibleForTesting131 boolean getIgnoreAllActualNullFields() {132 return ignoreAllActualNullFields;133 }134 @VisibleForTesting135 boolean getIgnoreAllExpectedNullFields() {136 return ignoreAllExpectedNullFields;137 }138 @VisibleForTesting139 boolean getIgnoreAllOverriddenEquals() {140 return ignoreAllOverriddenEquals;141 }142 /**143 * Sets whether actual empty optional fields are ignored in the recursive comparison.144 * <p>145 * See {@link RecursiveComparisonAssert#ignoringActualNullFields()} for code examples.146 *147 * @param ignoringAllActualEmptyOptionalFields whether to ignore actual empty optional fields in the recursive comparison148 */149 public void setIgnoreAllActualEmptyOptionalFields(boolean ignoringAllActualEmptyOptionalFields) {150 this.ignoreAllActualEmptyOptionalFields = ignoringAllActualEmptyOptionalFields;151 }152 @VisibleForTesting153 boolean getIgnoreAllActualEmptyOptionalFields() {154 return ignoreAllActualEmptyOptionalFields;155 }156 /**157 * Sets whether actual null fields are ignored in the recursive comparison.158 * <p>159 * See {@link RecursiveComparisonAssert#ignoringActualNullFields()} for code examples.160 *161 * @param ignoreAllActualNullFields whether to ignore actual null fields in the recursive comparison162 */163 public void setIgnoreAllActualNullFields(boolean ignoreAllActualNullFields) {164 this.ignoreAllActualNullFields = ignoreAllActualNullFields;165 }166 /**167 * Sets whether expected null fields are ignored in the recursive comparison.168 * <p>169 * See {@link RecursiveComparisonAssert#ignoringExpectedNullFields()} for code examples.170 *171 * @param ignoreAllExpectedNullFields whether to ignore expected null fields in the recursive comparison172 */173 public void setIgnoreAllExpectedNullFields(boolean ignoreAllExpectedNullFields) {174 this.ignoreAllExpectedNullFields = ignoreAllExpectedNullFields;175 }176 /**177 * Adds the given fields to the set of fields from the object under test to ignore in the recursive comparison.178 * <p>179 * The fields are ignored by name, not by value.180 * <p>181 * See {@link RecursiveComparisonAssert#ignoringFields(String...) RecursiveComparisonAssert#ignoringFields(String...)} for examples.182 *183 * @param fieldsToIgnore the fields of the object under test to ignore in the comparison.184 */185 public void ignoreFields(String... fieldsToIgnore) {186 List<String> fieldLocations = list(fieldsToIgnore);187 ignoredFields.addAll(fieldLocations);188 }189 /**190 * Adds the given fields and their subfields to the set of fields from the object under test to compare (no other fields will be compared).191 * <p>192 * The fields are specified by name, not by value, you can specify {@code person.name} but not {@code "Jack"} as {@code "Jack"} is not a field value.193 * <p>194 * Specifying a field will make all its subfields to be compared, for example specifying {@code person} will lead to compare {@code person.name}, {@code person.address} ...195 * on the other hand if you specify {@code person.name}, {@code person} won't be compared but {@code person.name} will be.196 * <p>197 * See {@link RecursiveComparisonAssert#comparingOnlyFields(String...) RecursiveComparisonAssert#comparingOnlyFields(String...)} for examples.198 *199 * @param fieldNamesToCompare the fields of the object under test to compare in the comparison.200 */201 public void compareOnlyFields(String... fieldNamesToCompare) {202 Stream.of(fieldNamesToCompare).map(FieldLocation::new).forEach(comparedFields::add);203 }204 /**205 * Allows to ignore in the recursive comparison the object under test fields matching the given regexes. The given regexes are added to the already registered ones.206 * <p>207 * See {@link RecursiveComparisonAssert#ignoringFieldsMatchingRegexes(String...) RecursiveComparisonAssert#ignoringFieldsMatchingRegexes(String...)} for examples.208 *209 * @param regexes regexes used to ignore fields in the comparison.210 */211 public void ignoreFieldsMatchingRegexes(String... regexes) {212 List<Pattern> patterns = Stream.of(regexes)213 .map(Pattern::compile)214 .collect(toList());215 ignoredFieldsRegexes.addAll(patterns);216 }217 /**218 * Adds the given types to the list fields from the object under test types to ignore in the recursive comparison.219 * The fields are ignored if their types exactly match one of the ignored types, if a field is a subtype of an ignored type it won't be ignored.220 * <p>221 * Note that if some object under test fields are null, they are not ignored by this method as their type can't be evaluated.222 * <p>223 * See {@link RecursiveComparisonAssert#ignoringFields(String...) RecursiveComparisonAssert#ignoringFieldsOfTypes(Class...)} for examples.224 *225 * @param types the types of the object under test to ignore in the comparison.226 */227 public void ignoreFieldsOfTypes(Class<?>... types) {228 stream(types).map(RecursiveComparisonConfiguration::asWrapperIfPrimitiveType).forEach(ignoredTypes::add);229 }230 private static Class<?> asWrapperIfPrimitiveType(Class<?> type) {231 if (!type.isPrimitive()) return type;232 if (type.equals(boolean.class)) return Boolean.class;233 if (type.equals(byte.class)) return Byte.class;234 if (type.equals(int.class)) return Integer.class;235 if (type.equals(short.class)) return Short.class;236 if (type.equals(char.class)) return Character.class;237 if (type.equals(float.class)) return Float.class;238 if (type.equals(double.class)) return Double.class;239 // should not arrive here since we have tested primitive types first240 return type;241 }242 /**243 * Returns the set of fields from the object under test to ignore in the recursive comparison.244 *245 * @return the set of fields from the object under test to ignore in the recursive comparison.246 */247 public Set<String> getIgnoredFields() {248 return ignoredFields;249 }250 /**251 * Returns the set of fields to compare from the object under test (no other fields will be compared).252 *253 * @return the set of fields from the object under test to compare.254 */255 public Set<FieldLocation> getComparedFields() {256 return comparedFields;257 }258 /**259 * Returns the set of fields from the object under test types to ignore in the recursive comparison.260 *261 * @return the set of fields from the object under test types to ignore in the recursive comparison.262 */263 public Set<Class<?>> getIgnoredTypes() {264 return ignoredTypes;265 }266 /**267 * Force a recursive comparison on all fields (except java types).268 * <p>269 * See {@link RecursiveComparisonAssert#ignoringAllOverriddenEquals()} for examples.270 */271 public void ignoreAllOverriddenEquals() {272 ignoreAllOverriddenEquals = true;273 }274 /**275 * Force a recursive comparison on all fields (except java types).276 * <p>277 * See {@link RecursiveComparisonAssert#usingOverriddenEquals()} for examples.278 */279 public void useOverriddenEquals() {280 ignoreAllOverriddenEquals = false;281 }282 /**283 * Adds the given fields to the list of fields to force a recursive comparison on.284 * <p>285 * See {@link RecursiveComparisonAssert#ignoringOverriddenEqualsForFields(String...) RecursiveComparisonAssert#ignoringOverriddenEqualsForFields(String...)} for examples.286 *287 * @param fields the fields to force a recursive comparison on.288 */289 public void ignoreOverriddenEqualsForFields(String... fields) {290 List<String> fieldLocations = list(fields);291 ignoredOverriddenEqualsForFields.addAll(fieldLocations);292 }293 /**294 * Adds the given regexes to the list of regexes used find the fields to force a recursive comparison on.295 * <p>296 * See {@link RecursiveComparisonAssert#ignoringOverriddenEqualsForFieldsMatchingRegexes(String...) RecursiveComparisonAssert#ignoringOverriddenEqualsForFieldsMatchingRegexes(String...)} for examples.297 *298 * @param regexes regexes used to specify the fields we want to force a recursive comparison on.299 */300 public void ignoreOverriddenEqualsForFieldsMatchingRegexes(String... regexes) {301 ignoredOverriddenEqualsForFieldsMatchingRegexes.addAll(Stream.of(regexes)302 .map(Pattern::compile)303 .collect(toList()));304 }305 /**306 * Adds the given types to the list of types to force a recursive comparison on.307 * <p>308 * See {@link RecursiveComparisonAssert#ignoringOverriddenEqualsForTypes(Class...) RecursiveComparisonAssert#ignoringOverriddenEqualsForTypes(Class...)} for examples.309 *310 * @param types the types to the list of types to force a recursive comparison on.311 */312 public void ignoreOverriddenEqualsForTypes(Class<?>... types) {313 ignoredOverriddenEqualsForTypes.addAll(list(types));314 }315 @VisibleForTesting316 boolean getIgnoreCollectionOrder() {317 return ignoreCollectionOrder;318 }319 /**320 * Sets whether to ignore collection order in the comparison.321 * <p>322 * See {@link RecursiveComparisonAssert#ignoringCollectionOrder()} for code examples.323 *324 * @param ignoreCollectionOrder whether to ignore collection order in the comparison.325 */326 public void ignoreCollectionOrder(boolean ignoreCollectionOrder) {327 this.ignoreCollectionOrder = ignoreCollectionOrder;328 }329 /**330 * Adds the given fields to the list fields from the object under test to ignore collection order in the recursive comparison.331 * <p>332 * See {@link RecursiveComparisonAssert#ignoringCollectionOrderInFields(String...) RecursiveComparisonAssert#ignoringCollectionOrderInFields(String...)} for examples.333 *334 * @param fieldsToIgnoreCollectionOrder the fields of the object under test to ignore collection order in the comparison.335 */336 public void ignoreCollectionOrderInFields(String... fieldsToIgnoreCollectionOrder) {337 List<String> fieldLocations = list(fieldsToIgnoreCollectionOrder);338 ignoredCollectionOrderInFields.addAll(fieldLocations);339 }340 /**341 * Returns the list fields from the object under test to ignore collection order in the recursive comparison.342 *343 * @return the list fields from the object under test to ignore collection order in the recursive comparison.344 */345 public Set<String> getIgnoredCollectionOrderInFields() {346 return ignoredCollectionOrderInFields;347 }348 /**349 * Adds the given regexes to the list of regexes used to find the object under test fields to ignore collection order in the recursive comparison.350 * <p>351 * See {@link RecursiveComparisonAssert#ignoringCollectionOrderInFieldsMatchingRegexes(String...) RecursiveComparisonAssert#ignoringCollectionOrderInFieldsMatchingRegexes(String...)} for examples.352 *353 * @param regexes regexes used to find the object under test fields to ignore collection order in in the comparison.354 */355 public void ignoreCollectionOrderInFieldsMatchingRegexes(String... regexes) {356 ignoredCollectionOrderInFieldsMatchingRegexes.addAll(Stream.of(regexes)357 .map(Pattern::compile)358 .collect(toList()));359 }360 /**361 * Returns the list of regexes used to find the object under test fields to ignore collection order in the recursive comparison.362 *363 * @return the list of regexes used to find the object under test fields to ignore collection order in the recursive comparison.364 */365 public List<Pattern> getIgnoredCollectionOrderInFieldsMatchingRegexes() {366 return ignoredCollectionOrderInFieldsMatchingRegexes;367 }368 /**369 * Registers the given {@link Comparator} to compare the fields with the given type.370 * <p>371 * Comparators registered with this method have less precedence than comparators registered with372 * {@link #registerComparatorForFields(Comparator, String...)}.373 * <p>374 * Note that registering a {@link Comparator} for a given type will override the previously registered BiPredicate/Comparator (if any).375 * <p>376 * See {@link RecursiveComparisonAssert#withComparatorForType(Comparator, Class)} for examples.377 *378 * @param <T> the class type to register a comparator for379 * @param comparator the {@link java.util.Comparator Comparator} to use to compare the given type380 * @param type the type to be compared with the given comparator.381 * @throws NullPointerException if the given comparator is null.382 */383 public <T> void registerComparatorForType(Comparator<? super T> comparator, Class<T> type) {384 requireNonNull(comparator, "Expecting a non null Comparator");385 typeComparators.registerComparator(type, comparator);386 }387 /**388 * Registers the given {@link BiPredicate} to compare the fields with the given type.389 * <p>390 * BiPredicates specified with this method have less precedence than the ones registered with391 * {@link #registerEqualsForFields(BiPredicate, String...)}392 * or comparators registered with {@link #registerComparatorForFields(Comparator, String...)}.393 * <p>394 * Note that registering a {@link BiPredicate} for a given type will override the previously registered BiPredicate/Comparator (if any).395 * <p>396 * See {@link RecursiveComparisonAssert#withEqualsForType(BiPredicate, Class)} for examples.397 *398 * @param <T> the class type to register a comparator for399 * @param equals the equals implementation to compare the given type400 * @param type the type to be compared with the given equals implementation .401 * @throws NullPointerException if the given BiPredicate is null.402 * @since 3.17.0403 */404 @SuppressWarnings("unchecked")405 public <T> void registerEqualsForType(BiPredicate<? super T, ? super T> equals, Class<T> type) {406 registerComparatorForType(toComparator(equals), type);407 }408 /**409 * Registers the given {@link Comparator} to compare the fields at the given locations.410 * <p>411 * The fields must be specified from the root object, for example if {@code Foo} has a {@code Bar} field and both have an {@code id} field,412 * one can register a comparator for Foo and Bar's {@code id} by calling:413 * <pre><code class='java'> registerComparatorForFields(idComparator, "foo.id", "foo.bar.id")</code></pre>414 * <p>415 * Comparators registered with this method have precedence over comparators registered with {@link #registerComparatorForType(Comparator, Class)}.416 * <p>417 * Note that registering a {@link Comparator} for a given field will override the previously registered BiPredicate/Comparator (if any).418 * <p>419 * See {@link RecursiveComparisonAssert#withComparatorForFields(Comparator, String...) RecursiveComparisonAssert#withComparatorForFields(Comparator, String...)} for examples.420 *421 * @param comparator the {@link java.util.Comparator Comparator} to use to compare the given field422 * @param fieldLocations the locations from the root object of the fields the comparator should be used for423 * @throws NullPointerException if the given comparator is null.424 */425 public void registerComparatorForFields(Comparator<?> comparator, String... fieldLocations) {426 requireNonNull(comparator, "Expecting a non null Comparator");427 Stream.of(fieldLocations).forEach(fieldLocation -> fieldComparators.registerComparator(fieldLocation, comparator));428 }429 /**430 * Registers the given {@link BiPredicate} to compare the fields at the given locations.431 * <p>432 * The fields must be specified from the root object, for example if {@code Foo} has a {@code Bar} field and both have an {@code id} field,433 * one can register a BiPredicate for Foo and Bar's {@code id} by calling:434 * <pre><code class='java'> registerEqualsForFields(idBiPredicate, "foo.id", "foo.bar.id")</code></pre>435 * <p>436 * BiPredicates registered with this method have precedence over the ones registered with {@link #registerEqualsForType(BiPredicate, Class)}437 * or the comparators registered with {@link #registerComparatorForType(Comparator, Class)}.438 * <p>439 * Note that registering a {@link BiPredicate} for a given field will override the previously registered BiPredicate/Comparator (if any).440 * <p>441 * See {@link RecursiveComparisonAssert#withEqualsForFields(BiPredicate, String...) RecursiveComparisonAssert#withEqualsForFields(BiPredicate, String...)} for examples.442 *443 * @param equals the equals implementation to compare the given fields.444 * @param fieldLocations the locations from the root object of the fields the comparator should be used for445 * @throws NullPointerException if the given BiPredicate is null.446 * @since 3.17.0447 */448 public void registerEqualsForFields(BiPredicate<?, ?> equals, String... fieldLocations) {449 registerComparatorForFields(toComparator(equals), fieldLocations);450 }451 /**452 * Registers the giving message which would be shown when differences in the given fields while comparison occurred.453 * <p>454 * The fields must be specified from the root object, for example if {@code Foo} has a {@code Bar} field and both455 * have an {@code id} field, one can register a message for Foo and Bar's {@code id} by calling:456 * <pre><code class='java'> registerErrorMessageForFields("some message", "foo.id", "foo.bar.id")</code></pre>457 * <p>458 * Messages registered with this method have precedence over the ones registered with {@link #registerErrorMessageForType(String, Class)}.459 * <p>460 * In case of {@code null} as message the default error message will be used (See {@link ComparisonDifference#DEFAULT_TEMPLATE}).461 *462 * @param message the error message that will be thrown when comparison error occurred463 * @param fieldLocations the field locations the error message should be used for464 */465 public void registerErrorMessageForFields(String message, String... fieldLocations) {466 Stream.of(fieldLocations).forEach(fieldLocation -> fieldMessages.registerMessage(fieldLocation, message));467 }468 /**469 * Registers the giving message which would be shown when differences for the giving type while comparison470 * occurred.471 * <p>472 * Message registered with this method have less precedence than the ones registered with {@link #registerErrorMessageForFields(String, String...)}.473 * <p>474 * In case of {@code null} as message the default error message will be used (See {@link ComparisonDifference#DEFAULT_TEMPLATE}).475 *476 * @param message the error message that will be thrown when comparison error occurred477 * @param clazz the type the error message should be used for478 */479 public void registerErrorMessageForType(String message, Class<?> clazz) {480 typeMessages.registerMessage(clazz, message);481 }482 /**483 * Sets whether the recursive comparison will check that actual's type is compatible with expected's type (the same applies for each field).484 * Compatible means that the expected's type is the same or a subclass of actual's type.485 * <p>486 * See {@link RecursiveComparisonAssert#withStrictTypeChecking()} for code examples.487 *488 * @param strictTypeChecking whether the recursive comparison will check that actual's type is compatible with expected's type.489 */490 public void strictTypeChecking(boolean strictTypeChecking) {491 this.strictTypeChecking = strictTypeChecking;492 }493 public boolean isInStrictTypeCheckingMode() {494 return strictTypeChecking;495 }496 public List<Pattern> getIgnoredFieldsRegexes() {497 return ignoredFieldsRegexes;498 }499 public List<Class<?>> getIgnoredOverriddenEqualsForTypes() {500 return ignoredOverriddenEqualsForTypes;501 }502 public List<String> getIgnoredOverriddenEqualsForFields() {503 return ignoredOverriddenEqualsForFields;504 }505 public List<Pattern> getIgnoredOverriddenEqualsForFieldsMatchingRegexes() {506 return ignoredOverriddenEqualsForFieldsMatchingRegexes;507 }508 public Stream<Entry<String, Comparator<?>>> comparatorByFields() {509 return fieldComparators.comparatorByFields();510 }511 @Override512 public String toString() {513 return multiLineDescription(CONFIGURATION_PROVIDER.representation());514 }515 @Override516 public int hashCode() {517 return java.util.Objects.hash(fieldComparators, ignoreAllActualEmptyOptionalFields, ignoreAllActualNullFields,518 ignoreAllExpectedNullFields, ignoreAllOverriddenEquals, ignoreCollectionOrder,519 ignoredCollectionOrderInFields, ignoredCollectionOrderInFieldsMatchingRegexes,520 ignoredFields,521 ignoredFieldsRegexes, ignoredOverriddenEqualsForFields,522 ignoredOverriddenEqualsForTypes,523 ignoredOverriddenEqualsForFieldsMatchingRegexes, ignoredTypes, strictTypeChecking,524 typeComparators, comparedFields, fieldMessages, typeMessages);525 }526 @Override527 public boolean equals(Object obj) {528 if (this == obj) return true;529 if (obj == null) return false;530 if (getClass() != obj.getClass()) return false;531 RecursiveComparisonConfiguration other = (RecursiveComparisonConfiguration) obj;532 return java.util.Objects.equals(fieldComparators, other.fieldComparators)533 && ignoreAllActualEmptyOptionalFields == other.ignoreAllActualEmptyOptionalFields534 && ignoreAllActualNullFields == other.ignoreAllActualNullFields535 && ignoreAllExpectedNullFields == other.ignoreAllExpectedNullFields536 && ignoreAllOverriddenEquals == other.ignoreAllOverriddenEquals537 && ignoreCollectionOrder == other.ignoreCollectionOrder538 && java.util.Objects.equals(ignoredCollectionOrderInFields, other.ignoredCollectionOrderInFields)539 && java.util.Objects.equals(ignoredFields, other.ignoredFields)540 && java.util.Objects.equals(comparedFields, other.comparedFields)541 && java.util.Objects.equals(ignoredFieldsRegexes, other.ignoredFieldsRegexes)542 && java.util.Objects.equals(ignoredOverriddenEqualsForFields, other.ignoredOverriddenEqualsForFields)543 && java.util.Objects.equals(ignoredOverriddenEqualsForTypes, other.ignoredOverriddenEqualsForTypes)544 && java.util.Objects.equals(ignoredOverriddenEqualsForFieldsMatchingRegexes,545 other.ignoredOverriddenEqualsForFieldsMatchingRegexes)546 && java.util.Objects.equals(ignoredTypes, other.ignoredTypes)547 && strictTypeChecking == other.strictTypeChecking548 && java.util.Objects.equals(typeComparators, other.typeComparators)549 && java.util.Objects.equals(ignoredCollectionOrderInFieldsMatchingRegexes,550 other.ignoredCollectionOrderInFieldsMatchingRegexes)551 && java.util.Objects.equals(fieldMessages, other.fieldMessages)552 && java.util.Objects.equals(typeMessages, other.typeMessages);553 }554 public String multiLineDescription(Representation representation) {555 StringBuilder description = new StringBuilder();556 describeIgnoreAllActualNullFields(description);557 describeIgnoreAllActualEmptyOptionalFields(description);558 describeIgnoreAllExpectedNullFields(description);559 describeComparedFields(description);560 describeIgnoredFields(description);561 describeIgnoredFieldsRegexes(description);562 describeIgnoredFieldsForTypes(description);563 describeOverriddenEqualsMethodsUsage(description, representation);564 describeIgnoreCollectionOrder(description);565 describeIgnoredCollectionOrderInFields(description);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 }853 private void describeRegisteredErrorMessagesForTypes(StringBuilder description) {854 if (!typeMessages.isEmpty()) {855 description.append("- these types had overridden error messages:%n");856 describeErrorMessagesForType(description);857 }858 }859 private void describeErrorMessagesForType(StringBuilder description) {860 String types = typeMessages.messageByTypes()861 .map(it -> it.getKey().getName())862 .collect(joining(DEFAULT_DELIMITER));863 description.append(format("%s %s%n", INDENT_LEVEL_2, types));864 }865 /**866 * Creates builder to build {@link RecursiveComparisonConfiguration}.867 * @return created builder868 */869 public static Builder builder() {870 return new Builder();871 }872 /**873 * Builder to build {@link RecursiveComparisonConfiguration}.874 */875 public static final class Builder {876 private boolean strictTypeChecking;877 private boolean ignoreAllActualNullFields;878 private boolean ignoreAllActualEmptyOptionalFields;879 private boolean ignoreAllExpectedNullFields;880 private String[] ignoredFields = {};881 private FieldLocation[] comparedFields = {};882 private String[] ignoredFieldsMatchingRegexes = {};883 private Class<?>[] ignoredTypes = {};884 private Class<?>[] ignoredOverriddenEqualsForTypes = {};885 private String[] ignoredOverriddenEqualsForFields = {};886 private String[] ignoredOverriddenEqualsForFieldsMatchingRegexes = {};887 private boolean ignoreAllOverriddenEquals = DEFAULT_IGNORE_ALL_OVERRIDDEN_EQUALS;888 private boolean ignoreCollectionOrder;889 private String[] ignoredCollectionOrderInFields = {};890 private String[] ignoredCollectionOrderInFieldsMatchingRegexes = {};891 private TypeComparators typeComparators = defaultTypeComparators();892 private FieldComparators fieldComparators = new FieldComparators();893 private FieldMessages fieldMessages = new FieldMessages();894 private TypeMessages typeMessages = new TypeMessages();895 private Builder() {}896 /**897 * Sets whether the recursive comparison will check that actual's type is compatible with expected's type (the same applies for each field).898 * Compatible means that the expected's type is the same or a subclass of actual's type.899 * <p>900 * See {@link RecursiveComparisonAssert#withStrictTypeChecking()} for code examples.901 *902 * @param strictTypeChecking whether the recursive comparison will check that actual's type is compatible with expected's type.903 * @return this builder.904 */905 public Builder withStrictTypeChecking(boolean strictTypeChecking) {906 this.strictTypeChecking = strictTypeChecking;907 return this;...

Full Screen

Full Screen

FieldMessages

Using AI Code Generation

copy

Full Screen

1import static org.assertj.core.api.Assertions.assertThat;2import static org.assertj.core.api.Assertions.within;3import static org.assertj.core.api.recursive.comparison.FieldLocation.*;4import static org.assertj.core.api.recursive.comparison.RecursiveComparisonConfiguration.*;5import java.util.List;6import org.assertj.core.api.recursive.comparison.FieldLocation;7import org.assertj.core.api.recursive.comparison.RecursiveComparisonConfiguration;8import org.assertj.core.data.Percentage;9import org.junit.jupiter.api.Test;10public class RecursiveComparisonConfigurationTest {11 public void testFieldMessages() {12 RecursiveComparisonConfiguration configuration = new RecursiveComparisonConfiguration();13 configuration.getFieldComparatorsForRead().put("name", (actual, expected) -> {14 return actual.equals(expected);15 });16 configuration.getFieldComparatorsForRead().put("age", (actual, expected) -> {17 return actual.equals(expected);18 });19 configuration.getFieldComparatorsForRead().put("address", (actual, expected) -> {20 return actual.equals(expected);21 });22 configuration.getFieldComparatorsForRead().put("phone", (actual, expected) -> {23 return actual.equals(expected);24 });25 configuration.getFieldComparatorsForRead().put("email", (actual, expected) -> {26 return actual.equals(expected);27 });28 configuration.getFieldComparatorsForRead().put("salary", (actual, expected) -> {29 return actual.equals(expected);30 });31 configuration.getFieldComparatorsForRead().put("grade", (actual, expected) -> {32 return actual.equals(expected);33 });34 configuration.getFieldComparatorsForRead().put("hobbies", (actual, expected) -> {35 return actual.equals(expected);36 });37 configuration.getFieldComparatorsForRead().put("address.street", (actual, expected) -> {38 return actual.equals(expected);39 });40 configuration.getFieldComparatorsForRead().put("address.city", (actual, expected) -> {41 return actual.equals(expected);42 });43 configuration.getFieldComparatorsForRead().put("address.state", (actual, expected) -> {44 return actual.equals(expected);45 });46 configuration.getFieldComparatorsForRead().put("address.zipcode", (actual, expected) -> {47 return actual.equals(expected);48 });49 configuration.getFieldComparatorsForRead().put("address.country", (actual, expected) -> {50 return actual.equals(expected);51 });52 configuration.getFieldComparatorsForRead().put("address.street", (actual, expected

Full Screen

Full Screen

FieldMessages

Using AI Code Generation

copy

Full Screen

1import static org.assertj.core.api.Assertions.assertThat;2import static org.assertj.core.api.Assertions.within;3import static org.assertj.core.api.recursive.comparison.RecursiveComparisonConfiguration.*;4import org.assertj.core.api.recursive.comparison.RecursiveComparisonConfiguration;5import org.junit.jupiter.api.Test;6public class RecursiveComparisonConfigurationTest {7 public void testRecursiveComparisonConfiguration() {8 RecursiveComparisonConfiguration configuration = new RecursiveComparisonConfiguration();9 configuration.setFieldComparatorsByPropertyOrFieldNames(fieldComparatorsByPropertyOrFieldNames);10 configuration.setFieldComparatorsByTypes(fieldComparatorsByTypes);11 configuration.setFieldMatcherByPropertyOrFieldNames(fieldMatcherByPropertyOrFieldNames);12 configuration.setFieldMatcherByTypes(fieldMatcherByTypes);13 configuration.setIgnoredFields(ignoredFields);14 configuration.setIgnoredOverriddenEqualsForTypes(ignoredOverriddenEqualsForTypes);15 configuration.setIgnoredOverriddenEqualsForFields(ignoredOverriddenEqualsForFields);16 configuration.setIgnoredFieldsRegex(ignoredFieldsRegex);17 configuration.setIgnoredOverriddenEqualsForFieldsRegex(ignoredOverriddenEqualsForFieldsRegex);18 configuration.setIgnoredOverriddenEqualsForTypesRegex(ignoredOverriddenEqualsForTypesRegex);19 configuration.setIgnoreAllActualNullFields(ignoreAllActualNullFields);20 configuration.setIgnoreAllExpectedNullFields(ignoreAllExpectedNullFields);21 configuration.setIgnoreCollectionOrder(ignoreCollectionOrder);

Full Screen

Full Screen

FieldMessages

Using AI Code Generation

copy

Full Screen

1import org.assertj.core.api.recursive.comparison.RecursiveComparisonConfiguration2def configuration = new RecursiveComparisonConfiguration()3configuration.setFieldComparators(4 new org.assertj.core.api.recursive.comparison.FieldByFieldComparator()5configuration.setFieldComparators(6 new org.assertj.core.api.recursive.comparison.FieldByFieldComparator(7 new org.assertj.core.api.recursive.comparison.FieldComparator() {8 boolean areEqual(Object actual, Object expected) {9 if (actual instanceof java.util.Date && expected instanceof java.util.Date) {10 }11 }12 }13assertThat(actual).usingRecursiveComparison(configuration).isEqualTo(expected)14import org.assertj.core.api.recursive.comparison.RecursiveComparisonConfiguration15def configuration = new RecursiveComparisonConfiguration()16configuration.setFieldComparators(17 new org.assertj.core.api.recursive.comparison.FieldByFieldComparator()18configuration.setFieldComparators(19 new org.assertj.core.api.recursive.comparison.FieldByFieldComparator(20 new org.assertj.core.api.recursive.comparison.FieldComparator() {21 boolean areEqual(Object actual, Object expected) {22 if (actual instanceof java.util.Date && expected instanceof java.util.Date) {23 }24 }25 }26assertThat(actual).usingRecursiveComparison(configuration).isEqualTo(expected)27import org.assertj.core.api.recursive.comparison.RecursiveComparisonConfiguration28def configuration = new RecursiveComparisonConfiguration()29configuration.setFieldByFieldElementComparator(30 new org.assertj.core.api.recursive.comparison.FieldByFieldElementComparator()31configuration.setFieldByFieldElementComparator(32 new org.assertj.core.api.recursive.comparison.FieldByFieldElementComparator(33 new org.assertj.core.api.recursive.comparison.FieldComparator() {34 boolean areEqual(Object actual, Object expected) {35 if (actual instanceof java.util.Date && expected instanceof java.util.Date) {36 }37 }38 }39assertThat(actual).usingRecursiveComparison(configuration).isEqualTo(expected)40import org.assertj.core.api.recursive.com

Full Screen

Full Screen

FieldMessages

Using AI Code Generation

copy

Full Screen

1FieldMessages fieldMessages = FieldMessages.instance()2 .ofType("java.time.ZonedDateTime", "should be a valid date")3 .ofType("java.time.LocalDate", "should be a valid date")4 .ofType("java.time.LocalDateTime", "should be a valid date")5 .ofType("java.time.LocalTime", "should be a valid time")6 .ofType("java.time.ZoneId", "should be a valid zone")7 .ofType("java.time.ZoneOffset", "should be a valid offset")8 .ofType("java.time.Duration", "should be a valid duration")9 .ofType("java.time.Period", "should be a valid period")10 .ofType("java.time.Year", "should be a valid year")11 .ofType("java.time.YearMonth", "should be a valid year-month")12 .ofType("java.time.MonthDay", "should be a valid month-day")13 .ofType("java.time.OffsetTime", "should be a valid offset-time")14 .ofType("java.time.OffsetDateTime", "should be a valid offset-date-time")15 .ofType("java.time.Instant", "should be a valid instant")16 .ofType("java.time.chrono.ChronoLocalDate", "should be a valid date")17 .ofType("java.time.chrono.ChronoLocalDateTime", "should be a valid date")18 .ofType("java.time.chrono.ChronoZonedDateTime", "should be a valid date")19 .ofType("java.time.chrono.ChronoPeriod", "should be a valid period")20 .ofType("java.time.chrono.ChronoLocalDate", "should be a valid date")21 .ofType("java.time.chrono.ChronoLocalDateTime", "should be a valid date")22 .ofType("java.time.chrono.ChronoZonedDateTime", "should be a valid date")23 .ofType("java.time.chrono.ChronoPeriod", "should be a valid period")24 .ofType("java.time.chrono.ChronoLocalDate", "should be a valid date")25 .ofType("java.time.chrono.ChronoLocalDateTime", "should be a valid date")26 .ofType("java.time.chrono.ChronoZonedDateTime", "should be a

Full Screen

Full Screen

FieldMessages

Using AI Code Generation

copy

Full Screen

1import static org.assertj.core.api.Assertions.*;2import static org.assertj.core.api.recursive.comparison.FieldTypeComparators.byAbsValue;3import static org.assertj.core.api.recursive.comparison.FieldTypeComparators.byAllFieldsExcept;4import static org.assertj.core.api.recursive.comparison.FieldTypeComparators.byAllFieldsOf;5import static org.assertj.core.api.recursive.comparison.FieldTypeComparators.byExpectedType;6import static org.assertj.core.api.recursive.comparison.FieldTypeComparators.byType;7import static org.assertj.core.api.recursive.comparison.FieldTypeComparators.byTypeIn;8import static org.assertj.core.api.recursive.comparison.FieldTypeComparators.byTypeMatching;9import static org.assertj.core.api.recursive.comparison.RecursiveComparisonConfiguration.*;10import java.util.regex.Pattern;11import org.assertj.core.api.recursive.comparison.FieldTypeComparators;12import org.assertj.core.api.recursive.comparison.RecursiveComparisonConfiguration;13import org.assertj.core.util.introspection.IntrospectionError;14RecursiveComparisonConfiguration config = new RecursiveComparisonConfiguration();15config = config.withFieldMessages(16 FieldMessages.forField("age").useMessage("age must be greater than 18"),17 FieldMessages.forField("name").useMessage("name must not be empty")18);19assertThat(new Person("John", 17)).usingRecursiveComparison(config)20 .isEqualTo(new Person("John", 17));21 <Person(name=John, age=17)>22 <Person(name=John, age=17)>23 <Person(name=John, age=17)>24 <Person(name=John, age=17)>

Full Screen

Full Screen

FieldMessages

Using AI Code Generation

copy

Full Screen

1RecursiveComparisonConfiguration recursiveComparisonConfiguration = new RecursiveComparisonConfiguration();2recursiveComparisonConfiguration.setFieldMessages(3 new FieldLocation("field1"),4 new FieldLocation("field2"),5 new FieldLocation("field3"),6 new FieldLocation("field4")7);8assertThat(actualObject)9 .usingRecursiveComparison(recursiveComparisonConfiguration)10 .isEqualTo(expectedObject);11RecursiveComparisonConfiguration recursiveComparisonConfiguration = new RecursiveComparisonConfiguration();12recursiveComparisonConfiguration.setFieldMessages(13 new FieldLocation("field1", "field1 message"),14 new FieldLocation("field2", "field2 message"),15 new FieldLocation("field3", "field3 message"),16 new FieldLocation("field4", "field4 message")17);18assertThat(actualObject)19 .usingRecursiveComparison(recursiveComparisonConfiguration)20 .isEqualTo(expectedObject);21RecursiveComparisonConfiguration recursiveComparisonConfiguration = new RecursiveComparisonConfiguration();22recursiveComparisonConfiguration.setFieldMessages(23 new FieldLocation("field1", "field1 message"),24 new FieldLocation("field2", "field2 message"),25 new FieldLocation("field3", "field3 message"),26 new FieldLocation("field4", "field4 message")27);

Full Screen

Full Screen

Automation Testing Tutorials

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

LambdaTest Learning Hubs:

YouTube

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

Run Assertj automation tests on LambdaTest cloud grid

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

Most used method in RecursiveComparisonConfiguration

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful