如何使用 Hamcrest 检查双精度数组中的每个元素是否“关闭"?到另一个数组中的每个元素? [英] How can I use Hamcrest to check if each element in an array of doubles is "close" to each element in another array?

查看:15
本文介绍了如何使用 Hamcrest 检查双精度数组中的每个元素是否“关闭"?到另一个数组中的每个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想比较两个双精度数组.使用 vanilla JUnit,我可以做到:

I would like to compare two arrays of doubles. Using vanilla JUnit, I can do:

double[] a = new double[]{1.0, 2.0, 3.0};
double[] b = new double[]{1.0, 2.0, 3.0};
assertEquals(a, b, 1e-10);

我想知道如何使用 Hamcrest 做到这一点,最好不要创建自定义匹配器(如果可能).类似于对数组中的每个元素使用关闭"匹配器.

I would like to know how to do this using Hamcrest, preferably without creating custom Matchers (if possible). Something akin to using the "close" matcher for each element in an array.

推荐答案

如果你把 a 改为 Double[] 那么你可以做 assertThat(a, arrayCloseTo(b, .2)); 使用这个辅助方法:

If you change a to a Double[] then you can do assertThat(a, arrayCloseTo(b, .2)); with this helper method:

public static Matcher<Double[]> arrayCloseTo(double[] array, double error) {
    List<Matcher<? super Double>> matchers = new ArrayList<Matcher<? super Double>>();
    for (double d : array)
        matchers.add(closeTo(d, error));
    return arrayContaining(matchers);
}

您也可以使用原始数组来实现,但为此您需要一个自定义匹配器.

You can do it with a primitive array as well, but you will need a custom matcher for that.

这篇关于如何使用 Hamcrest 检查双精度数组中的每个元素是否“关闭"?到另一个数组中的每个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆