比较两组没有等于的类

时间:2018-02-02 22:10:11

标签: java junit assertj

我有一个课程:

public class Something {
   public String a;
   public String b;
}

假设我不能在类Something中编写equals或compare方法。

我的测试:

Set<Something> aSet;
Set<Something> otherSet;

assertEquals(aSet, otherSet);//Fails because it only compares references of elements and does not perform a deep comparision field by field

有没有办法断言两个集是否等于逐字段比较元素(没有在Something类中写入equals方法)?

3 个答案:

答案 0 :(得分:2)

Give a try to AssertJ, it provides a way to compare element field by field recursively, example:

// the Dude class does not override equals
Dude jon = new Dude("Jon", 1.2);
Dude sam = new Dude("Sam", 1.3);
jon.friend = sam;
sam.friend = jon;

Dude jonClone = new Dude("Jon", 1.2);
Dude samClone = new Dude("Sam", 1.3);
jonClone.friend = samClone;
samClone.friend = jonClone;

assertThat(asList(jon, sam)).usingRecursiveFieldByFieldElementComparator()
                            .contains(jonClone, samClone);

Another possibility is to compare collections using a specific element comparator so SomethingComparator in your case, this requires a bit more work than the first option but you have full control of the comparison.

Hope it helps!

答案 1 :(得分:1)

您可以使用Hamcrest Library并执行

assertThat( aSet, both(everyItem(isIn(otherSet))).and(containsInAnyOrder(aSet)));

答案 2 :(得分:0)

当我无法在遗留代码中实现equals/hashCode时,我遇到了类似的情况。

让我根据包装模式分享一个解决方案。你包装你的遗留类并在那里实现equals/hashCode。在测试中,您可以创建一组包装对象并通过常规方式对其进行测试。

public class SomethingTest {
    class SomethingWrapper {
        private final Something value;

        SomethingWrapper(Something value) {
            this.value = value;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;

            if (o == null || getClass() != o.getClass()) return false;

            SomethingWrapper that = (SomethingWrapper) o;

            return new EqualsBuilder()
                    .append(value.a, that.value.a)
                    .append(value.b, that.value.b)
                    .isEquals();
        }

        @Override
        public int hashCode() {
            return new HashCodeBuilder(17, 37)
                    .append(value.a)
                    .append(value.b)
                    .toHashCode();
        }
    }

    @Test
    public void compareSomethingSetsWithoutEquals() {
        final Set<Something> originalA = new HashSet<>();
        originalA.add(new Something("a1", "b1"));
        originalA.add(new Something("a2", "b2"));

        final Set<Something> originalB = new HashSet<>();
        originalB.add(new Something("a1", "b1"));
        originalB.add(new Something("a2", "b2"));

        final Set<SomethingWrapper> aWrappedSetA =
                originalA.stream().map(SomethingWrapper::new).collect(Collectors.toSet());

        final Set<SomethingWrapper> aWrappedSetB =
                originalB.stream().map(SomethingWrapper::new).collect(Collectors.toSet());

        assertEquals(aWrappedSetA, aWrappedSetB);
    }
}