我如何使用 JUnit 和 Hamcrest 比较双打?

How do I compare doubles using JUnit and Hamcrest?

我正在使用 JUnit 和 Hamcrest 编写单元测试。我一直在比较双精度值:

assertThat(result, is(0.5));

但是,我现在需要比较计算值,但我不想与完整的双精度值进行比较。相反,我想比较亲近度。

我发现了一个名为 IsCloseTo 的 class,但我不确定如何在 assertThat 中使用它,而且我在网上找不到任何示例。

执行以下操作的正确语法是什么?

// I can't do this as I need to know what methods/classes whatever I should be using
// isCloseTo doesn't exist.
assertThat(result, isCloseTo(0.5, 0.1)); 

刚刚计算出来,is 实际上是 returns 一个 Is 对象,所以我需要做的就是:

assertThat(result, new IsCloseTo(0.5, 0.1)); 

nickb 的回答更好。

您应该可以打电话给 Matchers.closeTo(double, double)。使用静态导入,它看起来像:

assertThat(result, closeTo(0.5, 0.1));

如果你使用

,你可以使这篇文章更好读
assertThat(actual, is(closeTo(expected, delta)));

import static org.hamcrest.Matchers.closeTo;
import static org.hamcrest.Matchers.is;