How to use getDifferences method of org.assertj.core.api.recursive.comparison.RecursiveComparisonDifferenceCalculator class

Best Assertj code snippet using org.assertj.core.api.recursive.comparison.RecursiveComparisonDifferenceCalculator.getDifferences

Source:RecursiveComparisonDifferenceCalculator.java Github

copy

Full Screen

...74 void addDifference(DualValue dualValue, String description, Object... args) {75 differences.add(new ComparisonDifference(dualValue.getPath(), dualValue.actual, dualValue.expected,76 format(description, args)));77 }78 public List<ComparisonDifference> getDifferences() {79 Collections.sort(differences);80 return differences;81 }82 public boolean hasDualValuesToCompare() {83 return !dualValuesToCompare.isEmpty();84 }85 public DualValue pickDualValueToCompare() {86 final DualValue dualValue = dualValuesToCompare.removeFirst();87 if (dualValue.hasPotentialCyclingValues()) {88 // visited dual values are here to avoid cycle, java types don't have cycle, there is no need to track them.89 // moreover this would make should_fix_1854_minimal_test to fail (see the test for a detailed explanation)90 visitedDualValues.add(dualValue);91 }92 return dualValue;93 }94 private void registerForComparison(DualValue dualValue) {95 if (!visitedDualValues.contains(dualValue)) dualValuesToCompare.addFirst(dualValue);96 }97 private void initDualValuesToCompare(Object actual, Object expected, List<String> parentPath, boolean isRootObject) {98 DualValue dualValue = new DualValue(parentPath, actual, expected);99 boolean mustCompareFieldsRecursively = mustCompareFieldsRecursively(isRootObject, dualValue);100 if (dualValue.hasNoNullValues() && dualValue.hasNoContainerValues() && mustCompareFieldsRecursively) {101 // disregard the equals method and start comparing fields102 Set<String> nonIgnoredActualFieldsNames = recursiveComparisonConfiguration.getNonIgnoredActualFieldNames(dualValue);103 if (!nonIgnoredActualFieldsNames.isEmpty()) {104 // fields to ignore are evaluated when adding their corresponding dualValues to dualValuesToCompare which filters105 // ignored fields according to recursiveComparisonConfiguration106 Set<String> expectedFieldsNames = getFieldsNames(expected.getClass());107 if (expectedFieldsNames.containsAll(nonIgnoredActualFieldsNames)) {108 // we compare actual fields vs expected, ignoring expected additional fields109 for (String nonIgnoredActualFieldName : nonIgnoredActualFieldsNames) {110 DualValue fieldDualValue = new DualValue(parentPath, nonIgnoredActualFieldName,111 COMPARISON.getSimpleValue(nonIgnoredActualFieldName, actual),112 COMPARISON.getSimpleValue(nonIgnoredActualFieldName, expected));113 dualValuesToCompare.addFirst(fieldDualValue);114 }115 } else {116 dualValuesToCompare.addFirst(dualValue);117 }118 } else {119 dualValuesToCompare.addFirst(dualValue);120 }121 } else {122 dualValuesToCompare.addFirst(dualValue);123 }124 // We need to remove already visited fields pair to avoid infinite recursion in case125 // parent -> set{child} with child having a reference back to parent126 // it occurs to unordered collection where we compare all possible combination of the collection elements recursively127 // --128 // remove visited values one by one, DualValue.equals correctly compare respective actual and expected fields by reference129 visitedDualValues.forEach(visitedDualValue -> dualValuesToCompare.stream()130 .filter(dualValueToCompare -> dualValueToCompare.equals(visitedDualValue))131 .findFirst()132 .ifPresent(dualValuesToCompare::remove));133 }134 private boolean mustCompareFieldsRecursively(boolean isRootObject, DualValue dualValue) {135 boolean noCustomComparisonForDualValue = !recursiveComparisonConfiguration.hasCustomComparator(dualValue)136 && !shouldHonorOverriddenEquals(dualValue, recursiveComparisonConfiguration);137 return isRootObject || noCustomComparisonForDualValue;138 }139 }140 /**141 * Compare two objects for differences by doing a 'deep' comparison. This will traverse the142 * Object graph and perform either a field-by-field comparison on each143 * object (if not .equals() method has been overridden from Object), or it144 * will call the customized .equals() method if it exists.145 * <p>146 *147 * This method handles cycles correctly, for example A-&gt;B-&gt;C-&gt;A.148 * Suppose a and a' are two separate instances of the A with the same values149 * for all fields on A, B, and C. Then a.deepEquals(a') will return an empty list. It150 * uses cycle detection storing visited objects in a Set to prevent endless151 * loops.152 *153 * @param actual Object one to compare154 * @param expected Object two to compare155 * @param recursiveComparisonConfiguration the recursive comparison configuration156 * @return the list of differences found or an empty list if objects are equivalent.157 * Equivalent means that all field values of both subgraphs are the same,158 * either at the field level or via the respectively encountered overridden159 * .equals() methods during traversal.160 */161 public List<ComparisonDifference> determineDifferences(Object actual, Object expected,162 RecursiveComparisonConfiguration recursiveComparisonConfiguration) {163 if (recursiveComparisonConfiguration.isInStrictTypeCheckingMode() && expectedTypeIsNotSubtypeOfActualType(actual, expected)) {164 return list(expectedAndActualTypeDifference(actual, expected));165 }166 List<String> rootPath = list();167 List<DualValue> visited = list();168 return determineDifferences(actual, expected, rootPath, true, visited, recursiveComparisonConfiguration);169 }170 // TODO keep track of ignored fields in an RecursiveComparisonExecution class ?171 private static List<ComparisonDifference> determineDifferences(Object actual, Object expected, List<String> parentPath,172 boolean isRootObject, List<DualValue> visited,173 RecursiveComparisonConfiguration recursiveComparisonConfiguration) {174 ComparisonState comparisonState = new ComparisonState(visited, recursiveComparisonConfiguration);175 comparisonState.initDualValuesToCompare(actual, expected, parentPath, isRootObject);176 while (comparisonState.hasDualValuesToCompare()) {177 final DualValue dualValue = comparisonState.pickDualValueToCompare();178 final List<String> currentPath = dualValue.getPath();179 final Object actualFieldValue = dualValue.actual;180 final Object expectedFieldValue = dualValue.expected;181 if (actualFieldValue == expectedFieldValue) continue;182 // Custom comparators take precedence over all other types of comparison183 if (recursiveComparisonConfiguration.hasCustomComparator(dualValue)) {184 if (!propertyOrFieldValuesAreEqual(dualValue, recursiveComparisonConfiguration)) comparisonState.addDifference(dualValue);185 // since we used a custom comparator we don't need to inspect the nested fields any further186 continue;187 }188 if (actualFieldValue == null || expectedFieldValue == null) {189 // one of the value is null while the other is not as we already know that actualFieldValue != expectedFieldValue190 comparisonState.addDifference(dualValue);191 continue;192 }193 if (dualValue.isExpectedAnEnum()) {194 compareAsEnums(dualValue, comparisonState, recursiveComparisonConfiguration);195 continue;196 }197 // TODO move hasFieldTypesDifference check into each compareXXX198 if (dualValue.isExpectedFieldAnArray()) {199 compareArrays(dualValue, comparisonState);200 continue;201 }202 // we compare ordered collections specifically as to be matching, each pair of elements at a given index must match.203 // concretely we compare: (col1[0] vs col2[0]), (col1[1] vs col2[1])...(col1[n] vs col2[n])204 if (dualValue.isExpectedFieldAnOrderedCollection()205 && !recursiveComparisonConfiguration.shouldIgnoreCollectionOrder(dualValue)) {206 compareOrderedCollections(dualValue, comparisonState);207 continue;208 }209 if (dualValue.isExpectedFieldAnIterable()) {210 compareUnorderedIterables(dualValue, comparisonState);211 continue;212 }213 if (dualValue.isExpectedFieldAnOptional()) {214 compareOptional(dualValue, comparisonState);215 continue;216 }217 // Compare two SortedMaps taking advantage of the fact that these Maps can be compared in O(N) time due to their ordering218 if (dualValue.isExpectedFieldASortedMap()) {219 compareSortedMap(dualValue, comparisonState);220 continue;221 }222 // Compare two Unordered Maps. This is a slightly more expensive comparison because order cannot be assumed, therefore a223 // temporary Map must be created, however the comparison still runs in O(N) time.224 if (dualValue.isExpectedFieldAMap()) {225 compareUnorderedMap(dualValue, comparisonState);226 continue;227 }228 if (shouldCompareDualValue(recursiveComparisonConfiguration, dualValue)) {229 if (!actualFieldValue.equals(expectedFieldValue)) comparisonState.addDifference(dualValue);230 continue;231 }232 Class<?> actualFieldValueClass = actualFieldValue.getClass();233 Class<?> expectedFieldClass = expectedFieldValue.getClass();234 if (recursiveComparisonConfiguration.isInStrictTypeCheckingMode() && expectedTypeIsNotSubtypeOfActualType(dualValue)) {235 comparisonState.addDifference(dualValue, STRICT_TYPE_ERROR, expectedFieldClass.getName(),236 actualFieldValueClass.getName());237 continue;238 }239 Set<String> actualNonIgnoredFieldsNames = recursiveComparisonConfiguration.getNonIgnoredActualFieldNames(dualValue);240 Set<String> expectedFieldsNames = getFieldsNames(expectedFieldClass);241 // Check if expected has more fields than actual, in that case the additional fields are reported as difference242 if (!expectedFieldsNames.containsAll(actualNonIgnoredFieldsNames)) {243 // report missing fields in actual244 Set<String> actualFieldsNamesNotInExpected = newHashSet(actualNonIgnoredFieldsNames);245 actualFieldsNamesNotInExpected.removeAll(expectedFieldsNames);246 String missingFields = actualFieldsNamesNotInExpected.toString();247 String expectedClassName = expectedFieldClass.getName();248 String actualClassName = actualFieldValueClass.getName();249 String missingFieldsDescription = format(MISSING_FIELDS, actualClassName, expectedClassName,250 expectedFieldClass.getSimpleName(), actualFieldValueClass.getSimpleName(),251 missingFields);252 comparisonState.addDifference(dualValue, missingFieldsDescription);253 } else { // TODO remove else to report more diff254 // compare actual's fields against expected :255 // - if actual has more fields than expected, the additional fields are ignored as expected is the reference256 for (String actualFieldName : actualNonIgnoredFieldsNames) {257 if (expectedFieldsNames.contains(actualFieldName)) {258 DualValue newDualValue = new DualValue(currentPath, actualFieldName,259 COMPARISON.getSimpleValue(actualFieldName, actualFieldValue),260 COMPARISON.getSimpleValue(actualFieldName, expectedFieldValue));261 comparisonState.registerForComparison(newDualValue);262 }263 }264 }265 }266 return comparisonState.getDifferences();267 }268 private static boolean shouldCompareDualValue(RecursiveComparisonConfiguration recursiveComparisonConfiguration,269 final DualValue dualValue) {270 return !recursiveComparisonConfiguration.shouldIgnoreOverriddenEqualsOf(dualValue)271 && hasOverriddenEquals(dualValue.actual.getClass());272 }273 // avoid comparing enum recursively since they contain static fields which are ignored in recursive comparison274 // this would make different field enum value to be considered the same!275 private static void compareAsEnums(final DualValue dualValue,276 ComparisonState comparisonState,277 RecursiveComparisonConfiguration recursiveComparisonConfiguration) {278 if (recursiveComparisonConfiguration.isInStrictTypeCheckingMode()) {279 // we can use == for comparison which checks both actual and expected values and types are the same280 if (dualValue.actual != dualValue.expected) comparisonState.addDifference(dualValue);...

Full Screen

Full Screen

getDifferences

Using AI Code Generation

copy

Full Screen

1import static org.assertj.core.api.Assertions.assertThat;2import static org.assertj.core.api.recursive.comparison.RecursiveComparisonDifferenceCalculator.getDifferences;3import static org.assertj.core.api.recursive.comparison.RecursiveComparisonDifferenceCalculator.isEqualTo;4import java.util.List;5import org.assertj.core.api.recursive.comparison.Difference;6import org.assertj.core.api.recursive.comparison.RecursiveComparisonDifferenceCalculator;7import org.junit.Test;8public class RecursiveComparisonDifferenceCalculatorTest {9 public void test_getDifferences() {10 RecursiveComparisonDifferenceCalculator calculator = new RecursiveComparisonDifferenceCalculator();11 List<Difference> differences = calculator.getDifferences("a", "b");12 assertThat(differences).hasSize(1);13 assertThat(differences.get(0).toString()).isEqualTo("expected: \"b\" but was: \"a\"");14 }15 public void test_isEqualTo() {16 assertThat(isEqualTo("a", "b")).isFalse();17 assertThat(isEqualTo("a", "a")).isTrue();18 }19}20package org.assertj.core.api.recursive.comparison;21import java.util.ArrayList;22import java.util.List;23import org.assertj.core.api.recursive.comparison.Difference;24import org.assertj.core.api.recursive.comparison.RecursiveComparisonDifferenceCalculator;25public class RecursiveComparisonDifferenceCalculator {26 private final List<Difference> differences = new ArrayList<>();27 public List<Difference> getDifferences(Object actual, Object expected) {28 if (isEqualTo(actual, expected)) {29 return differences;30 }31 differences.add(new Difference(actual, expected));32 return differences;33 }34 public static boolean isEqualTo(Object actual, Object expected) {35 return actual == null ? expected == null : actual.equals(expected);36 }37}38package org.assertj.core.api.recursive.comparison;39public class Difference {40 private final Object actual;41 private final Object expected;42 public Difference(Object actual, Object expected) {43 this.actual = actual;44 this.expected = expected;45 }46 public String toString() {47 return String.format("expected: \"%s\" but was: \"%s\"", expected, actual);48 }49}

Full Screen

Full Screen

getDifferences

Using AI Code Generation

copy

Full Screen

1List<RecursiveComparisonDifference> differences = RecursiveComparisonDifferenceCalculator.getDifferences(actual, expected);2assertThat(differences).isEmpty();3assertThat(actual).usingRecursiveComparison().isEqualTo(expected);4public static List<RecursiveComparisonDifference> getDifferences(Object actual, Object expected)5public static List<RecursiveComparisonDifference> getDifferences(Object actual, Object expected)6public static RecursiveComparisonAssert recursiveComparison(Object actual)7package com.journaldev.assertj.recursive.comparison;8import static org.assertj.core.api.Assertions.assertThat;9import java.util.List;10import org.assertj.core.api.recursive.comparison.RecursiveComparisonDifference;11import org.assertj.core.api.recursive.comparison.RecursiveComparisonDifferenceCalculator;

Full Screen

Full Screen

getDifferences

Using AI Code Generation

copy

Full Screen

1assertThat(actual).usingRecursiveComparison().ignoringFields("id").isEqualTo(expected);2assertThat(actual).usingRecursiveComparison().ignoringFields("id").isEqualTo(expected);3assertThat(actual).usingRecursiveComparison().ignoringFields("id").isEqualTo(expected);4assertThat(actual).usingRecursiveComparison().ignoringFields("id").isEqualTo(expected);5assertThat(actual).usingRecursiveComparison().ignoringFields("id").isEqualTo(expected);6assertThat(actual).usingRecursiveComparison().ignoringFields("id").isEqualTo(expected);7assertThat(actual).usingRecursiveComparison().ignoringFields("id").isEqualTo(expected);8assertThat(actual).usingRecursiveComparison().ignoringFields("id").isEqualTo(expected);9assertThat(actual).usingRecursiveComparison().ignoringFields("id").isEqualTo(expected);10assertThat(actual).usingRecursiveComparison().ignoringFields("id").isEqualTo(expected);11assertThat(actual).usingRecursiveComparison().ignoringFields("id").isEqualTo(expected);12assertThat(actual).usingRecursiveComparison().ignoringFields("id").isEqualTo(expected);13assertThat(actual).usingRecursiveComparison().ignoringFields("id").isEqualTo(expected);

Full Screen

Full Screen

getDifferences

Using AI Code Generation

copy

Full Screen

1import org.assertj.core.api.recursive.comparison.RecursiveComparisonDifferenceCalculator;2import java.util.List;3public class AssertJRecursiveComparisonDifferenceCalculator {4 public static void main(String[] args) {5 List<RecursiveComparisonDifference> differences = RecursiveComparisonDifferenceCalculator.getDifferences(6 new Person("John", 23, "New York"),7 new Person("John", 23, "New York"));8 differences.forEach(System.out::println);9 }10}11RecursiveComparisonDifference{path=, actual=Person{name='John', age=23, address='New York'}, expected=Person{name='John', age=23, address='New York'}}12RecursiveComparisonDifference{path=address, actual=New York, expected=New York}13RecursiveComparisonDifference{path=age, actual=23, expected=23}14RecursiveComparisonDifference{path=name, actual=John, expected=John}

Full Screen

Full Screen

getDifferences

Using AI Code Generation

copy

Full Screen

1import org.assertj.core.api.recursive.comparison.RecursiveComparisonDifferenceCalculator;2import org.assertj.core.api.recursive.comparison.Difference;3public class RecursiveComparisonDifferenceCalculatorGetDifferencesMethod {4 public static void main(String[] args) {5 RecursiveComparisonDifferenceCalculator recursiveComparisonDifferenceCalculator = new RecursiveComparisonDifferenceCalculator();6 Object expected = new Object();7 Object actual = new Object();8 Difference differences = recursiveComparisonDifferenceCalculator.getDifferences(expected, actual);9 System.out.println(differences);10 }11}

Full Screen

Full Screen

getDifferences

Using AI Code Generation

copy

Full Screen

1public class TestRecursiveComparisonDifferenceCalculator {2 public void testGetDifferences() {3 List<String> expected = Arrays.asList("one", "two", "three");4 List<String> actual = Arrays.asList("one", "two", "three", "four");5 List<RecursiveComparisonDifference> differences = getDifferences(expected, actual);6 assertThat(differences).hasSize(1);7 RecursiveComparisonDifference recursiveComparisonDifference = differences.get(0);8 assertThat(recursiveComparisonDifference.getActual()).isEqualTo("four");9 assertThat(recursiveComparisonDifference.getExpected()).isEqualTo(null);10 assertThat(recursiveComparisonDifference.getPath()).isEqualTo("[]");11 }12}13 at org.assertj.core.api.Assertions.fail(Assertions.java:1245)14 at org.assertj.core.api.Assertions.fail(Assertions.java:1214)15 at org.assertj.core.api.AbstractListAssert.hasSize(AbstractListAssert.java:357)16 at com.baeldung.recursive.comparison.TestRecursiveComparisonDifferenceCalculator.testGetDifferences(TestRecursiveComparisonDifferenceCalculator.java:25)

Full Screen

Full Screen

getDifferences

Using AI Code Generation

copy

Full Screen

1import org.assertj.core.api.recursive.comparison.*;2import java.util.*;3public class Main {4 public static void main(String[] args) {5 List<String> expected = Arrays.asList("a", "b", "c");6 List<String> actual = Arrays.asList("a", "b", "d");7 List<RecursiveComparisonDifference> differences = RecursiveComparisonDifferenceCalculator.getDifferences(expected, actual);8 differences.forEach(System.out::println);9 }10}

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