我怎样才能使用Hamcrest来检查双打数组中的每个元素是否“接近”。到另一个数组中的每个元素? [英] How can I use Hamcrest to check if each element in an array of doubles is "close" to each element in another array?

查看:136
本文介绍了我怎样才能使用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执行此操作,最好不要创建自定义匹配器(如果可能) 。类似于为数组中的每个元素使用close匹配器的东西。

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天全站免登陆