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

后端 未结 1 1200
无人共我
无人共我 2020-12-11 02:06

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         


        
相关标签:
1条回答
  • 2020-12-11 02:36

    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.

    0 讨论(0)
提交回复
热议问题