有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

junit比较Java bean忽略空/空集合差异

是否有一种简短的,通用的方法,本机的或通过一个公共库,使用一个equals方法断言两个bean为true,从而丢弃null集合和空集合之间集合字段的差异?我需要这个用于JUnit测试,所以测试依赖关系是可以的 例如:

class Bus {
    private List<String> passengers;
}

@Test
public void testEmptyBussesEqual() {
    Bus bus1 = new Bus(null);
    Bus bus2 = new Bus(new ArraysList<>());
    assertTrue(specialEqual(bus1, bus2));
}

到目前为止,我最好的尝试是使用AssertJ:

assertThat(bus1)
    .usingComparatorForType(new CustomListComparator(), List.class)
    .usingComparatorForType(new CustomMapComparator(), Map.class)
    .isEqualToComparingFieldByFieldRecursively(bus2);

每一个习惯。。。Comparator忽略空集合和空集合之间的差异,然后使用类似的方法递归地比较集合内容

我拥有的主要用例是DTO和域模型之间的映射。DTO可能有空字段以优化传输介质上的空间,而域模型可能更喜欢空集合以避免NullPointerException。映射代码必须经过单元测试,null和empty之间的差异导致了测试代码的笨拙。 当然,用例的一种替代方法可能是配置序列化/反序列化,但这无助于对映射器进行单元测试,因为为了健壮性,映射器仍然将空字段映射到空集合


共 (1) 个答案

  1. # 1 楼答案

    可能是UnitilsReflectionAssert类将帮助您解决问题:

    public static void assertReflectionEquals(Object expected,
                                              Object actual,
                                              ReflectionComparatorMode... modes)
                                       throws junit.framework.AssertionFailedError
    

    Asserts that two objects are equal. Reflection is used to compare all fields of these values. If they are not equal an AssertionFailedError is thrown. The comparator modes determine how strict to compare the values.

    public static void assertLenientEquals(String message,
                                           Object expected,
                                           Object actual)
                                    throws junit.framework.AssertionFailedError
    

    Asserts that two objects are equal. Reflection is used to compare all fields of these values. If they are not equal an AssertionFailedError is thrown. This is identical to assertReflectionEquals with lenient order and ignore defaults set as comparator modes.

    @Test
    public void testCollectionEquals() {
        Collection<String> expected = null;
        Collection<String> actual = new ArrayList<>();
        ReflectionAssert.assertReflectionEquals(expected, actual, ReflectionComparatorMode.IGNORE_DEFAULTS);
        ReflectionAssert.assertLenientEquals("Error message", expected, actual);
    }