hamcrest TypeSafeMatcher无法匹配double数组

时间:2015-01-28 11:20:23

标签: java unit-testing hamcrest

我写了这个匹配器来检查double[]

的内容
@SuppressWarnings({ "rawtypes", "unchecked" })
public static Matcher<double[]> isArrayCloseTo(double[] expected) {
    final double DELTA = 1e-10;
    List<Matcher<Double>> matchers = new ArrayList<>();
    for (double d : expected)
        matchers.add(new IsCloseTo(d, DELTA));
    return new IsArray(matchers.toArray(new Matcher[matchers.size()]));
}

我抑制了那些警告,因为对于没有泛型类型的数组我什么也做不了。该方法看起来很好,但总是失败:

assertThat(new double[] { .1 }, isArrayCloseTo(new double[] { .1 })); //fails

问题出在TypesafeMatcher, line 65expectedType.isInstance(item)expectedTypeObject.classitem[0.1]

我怀疑这个问题与我可以将我传递给Matcher的{​​{1}}数组一般化的事实有关,但我不知道如何修复这个。谁能告诉我如何匹配一系列双打?

1 个答案:

答案 0 :(得分:3)

最终可以追溯到double[]无法转换为Double[]这一事实,Matcher<double[]>转换为Matcher<Double[]>也是如此。

如果您可以将原始double[]的所有用途更改为Double[],那么您的方法可以正常工作。否则,您需要编写自己的自定义匹配器。我在下面包含了一个基于代码构建的自定义Matcher。

这基本上与此重复: How can I use Hamcrest to check if each element in an array of doubles is "close" to each element in another array?

@SuppressWarnings({"rawtypes", "unchecked"})
public static Matcher<double[]> isArrayCloseTo(double[] expected) {
    final double DELTA = 1e-10;
    List<Matcher<Double>> matchers = new ArrayList<>();
    for (double d : expected)
        matchers.add(new IsCloseTo(d, DELTA));

    return new CustomTypeSafeMatcher<double[]>("array that is close to" + Arrays.toString(expected)) {
        @Override
        protected boolean matchesSafely(double[] actual) {
            return new IsArray<Double>(matchers.toArray(new Matcher[matchers.size()]))
                    .matchesSafely(Arrays.stream(actual).boxed().toArray(Double[]::new));
        }
    };
}