Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
254 views
in Technique[技术] by (71.8m points)

java - How can I use Hamcrest to check if each element in an array of doubles is "close" to each element in another array?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...