在 JUnit 4 测试中,我有一个方法 getValues()
返回 List<Double>
我想与引用列表进行比较的对象。到目前为止,我找到的最佳解决方案是使用 org.hamcrest.collection.IsArray.hasItems
和 org.hamcrest.Matchers.closeTo
像这样:
assertThat(getValues(), hasItems(closeTo(0.2, EPSILON), closeTo(0.3, EPSILON)));
这对于只返回少量值的测试来说很顺利。但如果测试返回更多值,这绝对不是最佳方法。
我也试过下面的代码。垂头丧气到Matcher
之前 hasItems
代码编译需要:
List<Matcher<Double>> doubleMatcherList = new ArrayList<Matcher<Double>>();
doubleMatcherList.add(closeTo(0.2, EPSILON));
doubleMatcherList.add(closeTo(0.3, EPSILON));
assertThat(getValues(), (Matcher) hasItems(doubleMatcherList));
比较失败,我不明白为什么:
java.lang.AssertionError: Expected: (a collection containing <[a numeric value within <1.0E-6> of <0.2>, a numeric value within <1.0E-6> of <0.3>]>) got: <[0.2, 0.30000000000000004]>
有没有更好的方法来比较两个大的 double 列表?这里的难点在于,需要数值公差来验证 getValues()
的结果是否正确。等于我的引用列表。这种比较对于任何对象列表来说似乎都很容易,但对于 Double
列表则不然。 .
最佳答案
我认为这里正确的解决方案是自定义 Matcher .基本上类似于 IsIterableContainingInOrder仅适用于 double 并支持误差范围。
关于java - 如何在 JUnit 中比较两个 double 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36015216/