How can I use Hamcrest to check if each element in an array of doubles is “close” to each element in another array?

人盡茶涼 提交于 2019-11-27 06:47:30

问题


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);

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.


回答1:


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.



来源:https://stackoverflow.com/questions/10623458/how-can-i-use-hamcrest-to-check-if-each-element-in-an-array-of-doubles-is-close

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!