我写了这个匹配器来检查 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 65 : expectedType.isInstance(item)
,其中 expectedType
是 Object.class
而 item
是 [0.1 ]
。
我怀疑这个问题与我无法泛化传递给 IsArray
的 Matcher
数组有关,但我不知道如何解决这个问题。谁能告诉我应该如何匹配 double 数组?
它最终回到了一个事实 double[]
无法转换为 Double[]
, Matcher<double[]>
也是如此至 Matcher<Double[]>
.
如果你能改变你对原语的所有使用 double[]
至 Double[]
,那么您的方法就可以正常工作。否则,您将需要编写自己的自定义匹配器。我在下面包含了一个基于您的代码构建的自定义匹配器。
这基本上是这个的副本:
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));
}
};
}