【问题标题】:Junit assertEquals on objects with double fieldsJunit assertEquals 在具有双字段的对象上
【发布时间】:2026-01-14 22:20:03
【问题描述】:

我有两个对象列表。这些对象引用其他对象,而这些对象又包含双精度对象。我想使用 assertEquals 来测试这两个对象是否相同。我已经手动验证了它们是,但 assertEquals 仍然返回错误。我认为原因是由于精度问题,双打不一样。我知道我可以通过深入到双字段并使用 assertEquals(d1, d2, delta) 来解决这个问题,但这似乎很麻烦。是否有向 assertEquals (或其他方法)提供 delta 的方法,以便在遇到双精度时可以使用该 delta 进行比较?

【问题讨论】:

    标签: junit double-precision


    【解决方案1】:

    Hamcrest matchers 可能会使这更容易一些。您可以创建自定义Matcher(或FeatureMatcher - Is there a simple way to match a field using Hamcrest?),然后将其与closeTo 组合以测试双打,然后使用容器匹配器(How do I assert an Iterable contains elements with a certain property?)检查列表。

    例如,要检查一个列表是否正好包含一个 Thing,它有一个 getValue 方法返回大约 10

    Matcher<Thing> thingWithExpectedDouble =
        Matchers.<Thing>hasProperty("value", Matchers.closeTo(10, 0.0001));
    assertThat(listOfItems, Matchers.contains(thingWithExpectedDouble));
    

    【讨论】:

      最近更新 更多