Add method to DiffBuilder to allow appending from a DiffResult.

This commit is contained in:
Nick Manley 2016-01-24 01:27:30 -06:00 committed by pascalschumacher
parent 49455b78bf
commit f8b1f6e745
2 changed files with 65 additions and 0 deletions

View File

@ -949,6 +949,59 @@ public class DiffBuilder implements Builder<DiffResult> {
return this;
}
/**
* <p>
* Append diffs from another {@code DiffResult}.
* </p>
*
* <p>
* This method is useful if you want to compare properties which are
* themselves Diffable and would like to know which specific part of
* it is different.
* </p>
*
* <pre>
* public class Person implements Diffable&lt;Person&gt; {
* String name;
* Address address; // implements Diffable&lt;Address&gt;
*
* ...
*
* public DiffResult diff(Person obj) {
* return new DiffBuilder(this, obj, ToStringStyle.SHORT_PREFIX_STYLE)
* .append("name", this.name, obj.name)
* .append("address", this.address.diff(obj.address))
* .build();
* }
* }
* </pre>
*
* @param fieldName
* the field name
* @param diffResult
* the {@code DiffResult} to append
* @return this
*/
public DiffBuilder append(final String fieldName,
final DiffResult diffResult) {
if (fieldName == null) {
throw new IllegalArgumentException("Field name cannot be null");
}
if (diffResult == null) {
throw new IllegalArgumentException("Diff result cannot be null");
}
if (objectsTriviallyEqual) {
return this;
}
for (Diff<?> diff : diffResult.getDiffs()) {
append(fieldName + "." + diff.getFieldName(),
diff.getLeft(), diff.getRight());
}
return this;
}
/**
* <p>
* Builds a {@link DiffResult} based on the differences appended to this

View File

@ -411,6 +411,18 @@ public class DiffBuilderTest {
assertEquals(0, list.getNumberOfDiffs());
}
@Test
public void testDiffResult() {
final TypeTestClass class1 = new TypeTestClass();
final TypeTestClass class2 = new TypeTestClass();
class2.intField = 2;
final DiffResult list = new DiffBuilder(class1, class2, SHORT_STYLE)
.append("prop1", class1.diff(class2))
.build();
assertEquals(1, list.getNumberOfDiffs());
assertEquals("prop1.int", list.getDiffs().get(0).getFieldName());
}
@Test(expected=IllegalArgumentException.class)
public void testNullLhs() {