How to use comparingOnlyFields method of org.assertj.core.api.RecursiveComparisonAssert class

Best Assertj code snippet using org.assertj.core.api.RecursiveComparisonAssert.comparingOnlyFields

Source:RecursiveComparisonConfiguration.java Github

copy

Full Screen

...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;908 }909 /**910 * Sets whether actual null fields are ignored in the recursive comparison.911 * <p>912 * See {@link RecursiveComparisonAssert#ignoringActualNullFields()} for code examples.913 *914 * @param ignoreAllActualNullFields whether to ignore actual null fields in the recursive comparison915 * @return this builder.916 */917 public Builder withIgnoreAllActualNullFields(boolean ignoreAllActualNullFields) {918 this.ignoreAllActualNullFields = ignoreAllActualNullFields;919 return this;920 }921 /**922 * Sets whether actual empty optional fields are ignored in the recursive comparison.923 * <p>924 * See {@link RecursiveComparisonAssert#ignoringActualEmptyOptionalFields()} for code examples.925 *926 * @param ignoreAllActualEmptyOptionalFields whether to ignore actual empty optional fields in the recursive comparison927 * @return this builder.928 */929 public Builder withIgnoreAllActualEmptyOptionalFields(boolean ignoreAllActualEmptyOptionalFields) {930 this.ignoreAllActualEmptyOptionalFields = ignoreAllActualEmptyOptionalFields;931 return this;932 }933 /**934 * Sets whether expected null fields are ignored in the recursive comparison.935 * <p>936 * See {@link RecursiveComparisonAssert#ignoringExpectedNullFields()} for code examples.937 *938 * @param ignoreAllExpectedNullFields whether to ignore expected null fields in the recursive comparison939 * @return this builder.940 */941 public Builder withIgnoreAllExpectedNullFields(boolean ignoreAllExpectedNullFields) {942 this.ignoreAllExpectedNullFields = ignoreAllExpectedNullFields;943 return this;944 }945 /**946 * Adds the given fields to the set of fields from the object under test to ignore in the recursive comparison. Nested fields can be specified like this: home.address.street.947 * <p>948 * See {@link RecursiveComparisonAssert#ignoringFields(String...) RecursiveComparisonAssert#ignoringFields(String...)} for examples.949 *950 * @param fieldsToIgnore the fields of the object under test to ignore in the comparison.951 * @return this builder.952 */953 public Builder withIgnoredFields(String... fieldsToIgnore) {954 this.ignoredFields = fieldsToIgnore;955 return this;956 }957 /**958 * Adds the given fields to the set of fields from the object under test to compare in the recursive comparison.959 * <p>960 * Nested fields can be specified like this: home.address.street.961 * <p>962 * See {@link RecursiveComparisonAssert#comparingOnlyFields(String...)} for examples.963 *964 * @param fieldsToCompare the fields of the object under test to compare.965 * @return this builder.966 */967 public Builder withComparedFields(String... fieldsToCompare) {968 this.comparedFields = Stream.of(fieldsToCompare).map(FieldLocation::new).toArray(FieldLocation[]::new);969 return this;970 }971 /**972 * 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.973 * <p>974 * See {@link RecursiveComparisonAssert#ignoringFieldsMatchingRegexes(String...) RecursiveComparisonAssert#ignoringFieldsMatchingRegexes(String...)} for examples.975 *976 * @param regexes regexes used to ignore fields in the comparison....

Full Screen

Full Screen

Source:RecursiveComparisonAssert.java Github

copy

Full Screen

...216 * <p>217 * The fields are specified by name, not by value, for example you can specify {@code person.name} but not {@code "Jack"}218 * as {@code "Jack"} is not a field value.219 * <p>220 * {@code comparingOnlyFields} can be combined with ignoring fields methods to restrict further the fields actually compared,221 * the resulting compared fields = {specified compared fields} {@code -} {specified ignored fields}.<br>For example if the specified compared fields = {"foo", "bar", "baz"}222 * and the ignored fields = {"bar"} then only {"foo", "baz"} fields will be compared.223 * <p>224 * Usage example:225 * <pre><code class='java'> public class Person {226 * String name;227 * double height;228 * Home home = new Home();229 * }230 *231 * public class Home {232 * Address address = new Address();233 * }234 *235 * public static class Address {236 * int number;237 * String street;238 * }239 *240 * Person sherlock = new Person("Sherlock", 1.80);241 * sherlock.home.address.street = "Baker Street";242 * sherlock.home.address.number = 221;243 *244 * Person moriarty = new Person("Moriarty", 1.80);245 * moriarty.home.address.street = "Butcher Street";246 * moriarty.home.address.number = 221;247 *248 *249 * // assertion succeeds as name and home.address.street fields are not compared.250 * assertThat(sherlock).usingRecursiveComparison()251 * .comparingOnlyFields("height", "home.address.number")252 * .isEqualTo(moriarty);253 *254 * // assertion fails as home.address.street fields differ.255 * assertThat(sherlock).usingRecursiveComparison()256 * .comparingOnlyFields("height", "home")257 * .isEqualTo(moriarty);</code></pre>258 *259 * @param fieldNamesToCompare the fields of the object under test to compare in the comparison.260 * @return this {@link RecursiveComparisonAssert} to chain other methods.261 */262 public SELF comparingOnlyFields(String... fieldNamesToCompare) {263 recursiveComparisonConfiguration.compareOnlyFields(fieldNamesToCompare);264 return myself;265 }266 /**267 * Makes the recursive comparison to ignore all <b>actual null fields</b> (but note that the expected object null fields are used in the comparison).268 * <p>269 * Example:270 * <pre><code class='java'> public class Person {271 * String name;272 * double height;273 * Home home = new Home();274 * }275 *276 * public class Home {...

Full Screen

Full Screen

Source:BeanTypeVerify.java Github

copy

Full Screen

...117 anAssert = anAssert.ignoringFields(ignoreFields.toArray(new String[0]));118 }119 final Set<String> validateFields = instance.getValidateFields();120 if (CollectionUtils.isNotEmpty(validateFields)) {121 anAssert = anAssert.comparingOnlyFields(validateFields.toArray(new String[0]));122 }123 for (Map.Entry<Class<?>, BaseComp> entry : instance.getCompConfigs().entrySet()) {124 anAssert = anAssert.withComparatorForType(entry.getValue(), entry.getKey());125 }126 anAssert.isEqualTo(b);127 }128 } else {129 ObjectAssert<Object> anAssert = assertThat(a);130 final BaseComp comp = instance.getCompConfigs().get(target);131 if (comp != null) {132 anAssert = anAssert.usingComparator(comp);133 }134 anAssert.isEqualTo(b);135 }...

Full Screen

Full Screen

comparingOnlyFields

Using AI Code Generation

copy

Full Screen

1import org.assertj.core.api.Assertions;2import org.assertj.core.api.RecursiveComparisonAssert;3import org.assertj.core.api.RecursiveComparisonConfiguration;4import org.assertj.core.groups.Tuple;5import java.util.ArrayList;6import java.util.List;7public class 1 {8 public static void main(String[] args) {9 List<Department> departments = new ArrayList<>();10 departments.add(new Department("IT", "Information Technology"));11 departments.add(new Department("HR", "Human Resource"));12 departments.add(new Department("FIN", "Finance"));13 List<Employee> employees = new ArrayList<>();14 employees.add(new Employee("John", "Doe", "IT", 1000.0));15 employees.add(new Employee("Jane", "Doe", "HR", 2000.0));16 employees.add(new Employee("John", "Smith", "FIN", 3000.0));17 Company company1 = new Company("ABC", departments, employees);18 Company company2 = new Company("ABC", departments, employees);19 RecursiveComparisonConfiguration recursiveComparisonConfiguration = new RecursiveComparisonConfiguration();20 recursiveComparisonConfiguration.setIgnoreCollectionOrder(true);21 recursiveComparisonConfiguration.setIgnoreAllActualNullFields(true);22 recursiveComparisonConfiguration.setIgnoreAllExpectedNullFields(true);23 new RecursiveComparisonAssert<>(company1, recursiveComparisonConfiguration)24 .usingRecursiveComparison()25 .withStrictTypeChecking()26 .withIgnoredFields("departments", "employees")27 .comparingOnlyFields("name")28 .isEqualTo(company2);29 new RecursiveComparisonAssert<>(company1, recursiveComparisonConfiguration)30 .usingRecursiveComparison()31 .withStrictTypeChecking()32 .withIgnoredFields("departments", "employees")33 .comparingOnlyFields("departments.code")34 .isEqualTo(company2);35 new RecursiveComparisonAssert<>(company1, recursiveComparisonConfiguration)36 .usingRecursiveComparison()37 .withStrictTypeChecking()38 .withIgnoredFields("departments", "employees")39 .comparingOnlyFields("employees.firstName")40 .isEqualTo(company2);41 new RecursiveComparisonAssert<>(company1, recursiveComparisonConfiguration)42 .usingRecursiveComparison()43 .withStrictTypeChecking()44 .withIgnoredFields("departments", "employees")45 .comparingOnlyFields("employees.lastName")46 .isEqualTo(company2);47 new RecursiveComparisonAssert<>(company1, recursiveComparisonConfiguration)48 .usingRecursiveComparison()49 .withStrictTypeChecking()

Full Screen

Full Screen

comparingOnlyFields

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.RecursiveComparisonAssert.comparingOnlyFields;4import org.assertj.core.api.RecursiveComparisonAssert;5import org.assertj.core.api.RecursiveComparisonAssert.RecursiveComparisonConfiguration;6import org.assertj.core.util.introspection.IntrospectionError;7import org.assertj.core.util.introspection.IntrospectionError.IntrospectionErrorType;8import org.junit.Test;9import org.junit.runner.RunWith;10import org.springframework.beans.factory.annotation.Autowired;11import org.springframework.boot.test.context.SpringBootTest;12import org.springframework.test.context.junit4.SpringRunner;13import com.example.demo.DemoApplication;14import com.example.demo.model.Address;15import com.example.demo.model.Person;16import com.example.demo.model.PersonDto;17import com.example.demo.model.PersonDto2;18import com.example.demo.model.PersonDto3;19import com.example.demo.model.PersonDto4;20import com.example.demo.model.PersonDto5;21import com.example.demo.model.PersonDto6;22import com.example.demo.model.PersonDto7;23import com.example.demo.model.PersonDto8;24import com.example.demo.model.PersonDto9;25import com.example.demo.model.PersonDto10;26import com.example.demo.model.PersonDto11;27import com.example.demo.model.PersonDto12;28import com.example.demo.model.PersonDto13;29import com.example.demo.model.PersonDto14;30import com.example.demo.model.PersonDto15;31import com.example.demo.model.PersonDto16;32import com.example.demo.model.PersonDto17;33import com.example.demo.model.PersonDto18;34import com.example.demo.model.PersonDto19;35import com.example.demo.model.PersonDto20;36import com.example.demo.model.PersonDto21;37import com.example.demo.model.PersonDto22;38import com.example.demo.model.PersonDto23;39import com.example.demo.model.PersonDto24;40import com.example.demo.model.PersonDto25;41import com.example.demo.model.PersonDto26;42import com.example.demo.model.PersonDto27;43import com.example.demo.model.PersonDto28;44import com.example.demo.model.PersonDto29;45import com.example.demo.model.PersonDto30;46import com.example.demo.model.PersonDto31;47import com.example.demo.model.PersonDto32;48import com.example.demo.model.PersonDto33;49import com.example.demo.model.PersonDto34;50import com.example.demo.model.PersonDto35;51import com.example.demo.model.PersonDto36;52import com.example.demo.model.PersonDto37;53import com.example.demo.model.PersonDto38;54import com.example.demo.model.PersonDto39;

Full Screen

Full Screen

comparingOnlyFields

Using AI Code Generation

copy

Full Screen

1import static org.assertj.core.api.Assertions.assertThat;2public class 1 {3 public static void main(String[] args) {4 Person person1 = new Person("John", 25);5 Person person2 = new Person("John", 25);6 assertThat(person1).usingRecursiveComparison().comparingOnlyFields("name").isEqualTo(person2);7 }8}9import static org.assertj.core.api.Assertions.assertThat;10public class 2 {11 public static void main(String[] args) {12 Person person1 = new Person("John", 25);13 Person person2 = new Person("John", 25);14 assertThat(person1).usingRecursiveComparison().comparingOnlyFields("name").isEqualTo(person2);15 }16}17import static org.assertj.core.api.Assertions.assertThat;18public class 3 {19 public static void main(String[] args) {20 Person person1 = new Person("John", 25);21 Person person2 = new Person("John", 25);22 assertThat(person1).usingRecursiveComparison().comparingOnlyFields("name").isEqualTo(person2);23 }24}25import static org.assertj.core.api.Assertions.assertThat;26public class 4 {27 public static void main(String[] args) {28 Person person1 = new Person("John", 25);29 Person person2 = new Person("John", 25);30 assertThat(person1).usingRecursiveComparison().comparingOnlyFields("name").isEqualTo(person2);31 }32}33import static org.assertj.core.api.Assertions.assertThat;34public class 5 {35 public static void main(String[] args) {36 Person person1 = new Person("John", 25);37 Person person2 = new Person("John", 25);38 assertThat(person1).usingRecursiveComparison().comparingOnlyFields("name").isEqualTo(person2);39 }40}41import static org

Full Screen

Full Screen

comparingOnlyFields

Using AI Code Generation

copy

Full Screen

1import org.assertj.core.api.RecursiveComparisonAssert;2import org.assertj.core.api.Assertions;3import org.assertj.core.api.recursive.comparison.RecursiveComparisonConfiguration;4public class 1 {5 public static void main(String[] args) {6 RecursiveComparisonConfiguration config = RecursiveComparisonConfiguration.builder()7 .withIgnoredFields("field1", "field2").build();8 RecursiveComparisonAssert.assertThat(new A()).usingRecursiveComparison(config)9 .isEqualTo(new B());10 }11 static class A {12 String field1;13 String field2;14 String field3;15 public String getField1() {16 return field1;17 }18 public void setField1(String field1) {19 this.field1 = field1;20 }21 public String getField2() {22 return field2;23 }24 public void setField2(String field2) {25 this.field2 = field2;26 }27 public String getField3() {28 return field3;29 }30 public void setField3(String field3) {31 this.field3 = field3;32 }33 }34 static class B {35 String field3;36 public String getField3() {37 return field3;38 }39 public void setField3(String field3) {40 this.field3 = field3;41 }42 }43}44 A(field1=null, field2=null, field3=null)45 B(field3=null)46 A(field1=null, field2=null, field3=null)47 B(field3=null)

Full Screen

Full Screen

comparingOnlyFields

Using AI Code Generation

copy

Full Screen

1import static org.assertj.core.api.Assertions.assertThat;2import static org.assertj.core.api.Assertions.withinPercentage;3import static org.assertj.core.api.RecursiveComparisonAssert.recursiveComparison;4public class Test {5 public static void main(String[] args) {6 Person person = new Person("John", "Doe", 30);7 Person person2 = new Person("John", "Doe", 30);8 assertThat(person).usingRecursiveComparison().isEqualTo(person2);9 assertThat(person).usingRecursiveComparison().isEqualTo(person2);

Full Screen

Full Screen

comparingOnlyFields

Using AI Code Generation

copy

Full Screen

1package com.mycompany.app;2import static org.assertj.core.api.Assertions.*;3import static org.assertj.core.api.Assertions.assertThat;4import static org.assertj.core.api.Assertions.assertThatCode;5import static org.assertj.core.api.Assertions.assertThatThrownBy;6import static org.assertj.core.api.Assertions.catchThrowable;7import static org.assertj.core.api.Assertions.entry;8import static org.assertj.core.api.Assertions.fail;9import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType;10import static org.assertj.core.api.AssertionsForClassTypes.assertThatIllegalArgumentException;11import static org.assertj.core.api.AssertionsForClassTypes.assertThatNullPointerException;12import static org.assertj.core.api.AssertionsForClassTypes.catchThrowableOfType;13import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat;14import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThatCode;15import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThatThrownBy;16import static org.assertj.core.api.AssertionsForInterfaceTypes.catchThrowable;17import static org.assertj.core.api.AssertionsForInterfaceTypes.fail;18import static org.assertj.core.api.AssertionsForInterfaceTypes.catchThrowableOfType;19import java.util.ArrayList;20import java.util.List;21import java.util.Map;22import java.util.TreeMap;23import java.util.stream.Stream;24import org.junit.jupiter.api.Test;25import org.junit.jupiter.params.ParameterizedTest;26import org.junit.jupiter.params.provider.Arguments;27import org.junit.jupiter.params.provider.MethodSource;28import com.mycompany.app.Employee;29import com.mycompany.app.Employee.Address;30{31 public void shouldPassWhenComparingOnlyGivenFields() {32 Employee employee = new Employee(1L, "John", new Address("street", "city"), 1000);33 Employee otherEmployee = new Employee(1L, "John", new Address("street", "city"), 2000);34 assertThat(employee).usingRecursiveComparison()35 .ignoringAllOverriddenEquals()36 .ignoringFields("salary")37 .isEqualTo(otherEmployee);38 }39 public void shouldFailWhenComparingOnlyGivenFields() {40 Employee employee = new Employee(1L, "John", new Address("street", "city"), 1000);41 Employee otherEmployee = new Employee(1L, "John", new Address("street", "city"), 2000);42 assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThat(employee).usingRecursiveComparison()43 .ignoringAllOverriddenEquals()44 .ignoringFields("salary")

Full Screen

Full Screen

comparingOnlyFields

Using AI Code Generation

copy

Full Screen

1import org.assertj.core.api.RecursiveComparisonAssert;2public class Test {3 public static void main(String[] args) {4 Person person1 = new Person("John", "Doe", 30);5 Person person2 = new Person("John", "Doe", 30);6 RecursiveComparisonAssert.assertThat(person1).comparingOnlyFields("firstName", "lastName").isEqualTo(person2);7 }8}9public class Person {10 private String firstName;11 private String lastName;12 private int age;13 public Person(String firstName, String lastName, int age) {14 this.firstName = firstName;15 this.lastName = lastName;16 this.age = age;17 }18 public String getFirstName() {19 return firstName;20 }21 public String getLastName() {22 return lastName;23 }24 public int getAge() {25 return age;26 }27 public boolean equals(Object o) {28 if (this == o) return true;29 if (o == null || getClass() != o.getClass()) return false;30 Person person = (Person) o;31 Objects.equals(firstName, person.firstName) &&32 Objects.equals(lastName, person.lastName);33 }34 public int hashCode() {35 return Objects.hash(firstName, lastName, age);36 }37}38at org.assertj.core.api.RecursiveComparisonAssert.isEqualTo(RecursiveComparisonAssert.java:162)39at org.assertj.core.api.RecursiveComparisonAssert.isEqualTo(RecursiveComparisonAssert.java:145)40at Test.main(Test.java:9)

Full Screen

Full Screen

comparingOnlyFields

Using AI Code Generation

copy

Full Screen

1import org.junit.Test;2import static org.assertj.core.api.Assertions.*;3public class AssertJTest {4 public void test() {5 Employee e1 = new Employee(1, "John");6 Employee e2 = new Employee(1, "John");7 assertThat(e1).usingRecursiveComparison().isEqualTo(e2);8 }9}10public class Employee {11 private int id;12 private String name;13 public Employee(int id, String name) {14 this.id = id;15 this.name = name;16 }17 public int getId() {18 return id;19 }20 public String getName() {21 return name;22 }23}24at org.assertj.core.error.ShouldBeEqualByComparingFieldByFieldRecursively.shouldBeEqualByComparingFieldByFieldRecursively(ShouldBeEqualByComparingFieldByFieldRecursively.java:44)25at org.assertj.core.internal.objects.Objects.assertIsEqualToComparingFieldByFieldRecursively(Objects.java:280)26at org.assertj.core.api.RecursiveComparisonAssert.isEqualTo(RecursiveComparisonAssert.java:129)27at AssertJTest.test(AssertJTest.java:12)28at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)29at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)30at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)31at java.base/java.lang.reflect.Method.invoke(Method.java:566)32at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:686)33at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)34at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)35at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)36at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140)37at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension

Full Screen

Full Screen

comparingOnlyFields

Using AI Code Generation

copy

Full Screen

1public class Test {2 public static void main(String[] args) {3 Person person1 = new Person("John", "Doe", 25, new Address("123 Street", "New York"));4 Person person2 = new Person("John", "Doe", 25, new Address("123 Street", "New York"));5 assertThat(person1).usingRecursiveComparison().comparingOnlyFields("firstName", "lastName", "age").isEqualTo(person2);6 }7}8public class Person {9 private String firstName;10 private String lastName;11 private int age;12 private Address address;13 public Person(String firstName, String lastName, int age, Address address) {14 this.firstName = firstName;15 this.lastName = lastName;16 this.age = age;17 this.address = address;18 }19 public String getFirstName() {20 return firstName;21 }22 public String getLastName() {23 return lastName;24 }25 public int getAge() {26 return age;27 }28 public Address getAddress() {29 return address;30 }31}32public class Address {33 private String street;34 private String city;35 public Address(String street, String city) {36 this.street = street;37 this.city = city;38 }39 public String getStreet() {40 return street;41 }42 public String getCity() {43 return city;44 }45}46when recursively comparing field by field, but found the following difference(s):47at org.assertj.core.api.RecursiveComparisonAssert.isEqualTo(RecursiveComparisonAssert.java:283)48at org.assertj.core.api.RecursiveComparisonAssert.isEqualTo(RecursiveComparisonAssert.java:162)49at org.assertj.core.api.RecursiveComparisonAssert.isEqualTo(RecursiveComparisonAssert.java:145)50at Test.main(Test.java:9)

Full Screen

Full Screen

comparingOnlyFields

Using AI Code Generation

copy

Full Screen

1import org.junit.Test;2import static org.assertj.core.api.Assertions.*;3public class AssertJTest {4 public void test) {5 Employee e1 = new Employee(1, John");6 Employee e2 = new Employee(1, "John");7 assertThat(e1).usingRecursiveComparison().isEqualTo(e2);8 }9}10public class Employee {11 private int id;12 private String name;13 public Employee(int id, String name) {14 this.id = id;15 this.name = name;16 }17 public int getId() {18 return id;19 }20 public String getName() {21 return name;22 }23}24at org.assertj.core.error.ShouldBeEqualByComparingFieldByFieldRecursively.shouldBeEqualByComparingFieldByFieldRecursively(ShouldBeEqualByComparingFieldByFieldRecursively.java:44)25at org.assertj.core.internal.objects.Objects.assertIsEqualToComparingFieldByFieldRecursively(Objects.java:280)26at org.assertj.core.api.RecursiveComparisonAssert.isEqualTo(RecursiveComparisonAssert.java:129)27at AssertJTest.test(AssertJTest.java:12)28at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)29at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)30at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)31at java.base/java.lang.reflect.Method.invoke(Method.java:566)32at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:686)33at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)34at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)35at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)36at org.junit.jupiter.engine.extenion.TimeoutExtension.interceptTestbeMethod(TimeoutExtension.jva:140)37at og.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension

Full Screen

Full Screen

comparingOnlyFields

Using AI Code Generation

copy

Full Screen

1public class Test {2 public static void main(String[] args) {3 Person person1 = new Person("John", "Doe", 25, new Address("123 Street", "New York"));4 Person person2 = new Person("John", "Doe", 25, new Address("123 Street", "New York));5 assertThat(person1.usingRecursiveComparison().comparingOnlyFields("firstName", "lastName", "age").isEqualTo(person2);6 }7}8public class Person {9 private String firstName;10 private String lastName;11 private int age;12 private Address address;13 public Person(String firstName, String lastName, int age, Address address) {14 this.firstName = firstName;15 this.lastName = lastName;16 this.age = age;17 this.address = address;18 }19 public String getFirstName() {20 return firstName;21 }22 public String getLastName() {23 return lastName;24 }25 public int getAge() {26 return age;27 }28 public Address getAddress() {29 return address;30 }31}32public class Address {33 private String street;34 private String city;35 public Address(String street, String city) {36 this.street = street;37 this.city = city;38 }39 public String getStreet() {40 return street;41 }42 public String getCity() {43 return city;44 }45}46when recursively comparing field by field, but found the following difference(s):47at org.assertj.core.api.RecursiveComparisonAssert.isEqualTo(RecursiveComparisonAssert.java:283)48 A(field1=null, field2=null, field3=null)49 B(field3=null)

Full Screen

Full Screen

comparingOnlyFields

Using AI Code Generation

copy

Full Screen

1import static org.assertj.core.api.Assertions.assertThat;2import static org.assertj.core.api.Assertions.withinPercentage;3import static org.assertj.core.api.RecursiveComparisonAssert.recursiveComparison;4public class Test {5 public static void main(String[] args) {6 Person person = new Person("John", "Doe", 30);7 Person person2 = new Person("John", "Doe", 30);8 assertThat(person).usingRecursiveComparison().isEqualTo(person2);9 assertThat(person).usingRecursiveComparison().isEqualTo(person2);

Full Screen

Full Screen

comparingOnlyFields

Using AI Code Generation

copy

Full Screen

1package com.mycompany.app;2import static org.assertj.core.api.Assertions.*;3import static org.assertj.core.api.Assertions.assertThat;4import static org.assertj.core.api.Assertions.assertThatCode;5import static org.assertj.core.api.Assertions.assertThatThrownBy;6import static org.assertj.core.api.Assertions.catchThrowable;7import static org.assertj.core.api.Assertions.entry;8import static org.assertj.core.api.Assertions.fail;9import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType;10import static org.assertj.core.api.AssertionsForClassTypes.assertThatIllegalArgumentException;11import static org.assertj.core.api.AssertionsForClassTypes.assertThatNullPointerException;12import static org.assertj.core.api.AssertionsForClassTypes.catchThrowableOfType;13import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat;14import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThatCode;15import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThatThrownBy;16import static org.assertj.core.api.AssertionsForInterfaceTypes.catchThrowable;17import static org.assertj.core.api.AssertionsForInterfaceTypes.fail;18import static org.assertj.core.api.AssertionsForInterfaceTypes.catchThrowableOfType;19import java.util.ArrayList;20import java.util.List;21import java.util.Map;22import java.util.TreeMap;23import java.util.stream.Stream;24import org.junit.jupiter.api.Test;25import org.junit.jupiter.params.ParameterizedTest;26import org.junit.jupiter.params.provider.Arguments;27import org.junit.jupiter.params.provider.MethodSource;28import com.mycompany.app.Employee;29import com.mycompany.app.Employee.Address;30{31 public void shouldPassWhenComparingOnlyGivenFields() {32 Employee employee = new Employee(1L, "John", new Address("street", "city"), 1000);33 Employee otherEmployee = new Employee(1L, "John", new Address("street", "city"), 2000);34 assertThat(employee).usingRecursiveComparison()35 .ignoringAllOverriddenEquals()36 .ignoringFields("salary")37 .isEqualTo(otherEmployee);38 }39 public void shouldFailWhenComparingOnlyGivenFields() {40 Employee employee = new Employee(1L, "John", new Address("street", "city"), 1000);41 Employee otherEmployee = new Employee(1L, "John", new Address("street", "city"), 2000);42 assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThat(employee).usingRecursiveComparison()43 .ignoringAllOverriddenEquals()44 .ignoringFields("salary")

Full Screen

Full Screen

comparingOnlyFields

Using AI Code Generation

copy

Full Screen

1import org.junit.Test;2import static org.assertj.core.api.Assertions.*;3public class AssertJTest {4 public void test() {5 Employee e1 = new Employee(1, "John");6 Employee e2 = new Employee(1, "John");7 assertThat(e1).usingRecursiveComparison().isEqualTo(e2);8 }9}10public class Employee {11 private int id;12 private String name;13 public Employee(int id, String name) {14 this.id = id;15 this.name = name;16 }17 public int getId() {18 return id;19 }20 public String getName() {21 return name;22 }23}24at org.assertj.core.error.ShouldBeEqualByComparingFieldByFieldRecursively.shouldBeEqualByComparingFieldByFieldRecursively(ShouldBeEqualByComparingFieldByFieldRecursively.java:44)25at org.assertj.core.internal.objects.Objects.assertIsEqualToComparingFieldByFieldRecursively(Objects.java:280)26at org.assertj.core.api.RecursiveComparisonAssert.isEqualTo(RecursiveComparisonAssert.java:129)27at AssertJTest.test(AssertJTest.java:12)28at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)29at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)30at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)31at java.base/java.lang.reflect.Method.invoke(Method.java:566)32at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:686)33at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)34at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)35at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)36at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140)37at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension

Full Screen

Full Screen

Automation Testing Tutorials

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

LambdaTest Learning Hubs:

YouTube

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

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful