使用google test和google mock进行浮点数组比较

lea*_*vst 6 c++ arrays floating-point googletest googlemock

我是 Google 测试产品的新手,并使用一些信号处理代码来尝试它们。我试图断言浮点数组在某些范围内等于,使用谷歌模拟,如这个问题的答案所建议的。我想知道为如下表达式添加一些容错能力的推荐方法。。。

EXPECT_THAT(  impulse, testing::ElementsAreArray( std::vector<float>({
    0, 0, 0, 1, 1, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0
}) )  );
Run Code Online (Sandbox Code Playgroud)

我希望如果数组中的逐元素值彼此相差在 10 -8范围内,测试就能通过。

小智 8

以下对我有用:

using ::testing::Pointwise;
using ::testing::FloatNear;

auto const max_abs_error = 1 / 1024.f;
ASSERT_THAT(
    test,
    Pointwise(FloatNear(max_abs_error), ref));
Run Code Online (Sandbox Code Playgroud)

其中testref都是类型std::vector<float>


lea*_*vst 3

这是一种方法。首先在测试范围之外定义一个匹配器。根据文档,匹配器不能在类或函数中定义。。

MATCHER_P(FloatNearPointwise, tol, "Out of range") {
    return (std::get<0>(arg)>std::get<1>(arg)-tol && std::get<0>(arg)<std::get<1>(arg)+tol) ;
}
Run Code Online (Sandbox Code Playgroud)

然后就可以和Pointwiseint 一起使用进行测试了。。。

std::vector<float> expected_array({
    0, 0, 0, 1, 1, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0
});

EXPECT_THAT(  impulse, Pointwise( FloatNearPointwise(1e-8), expected_array  ) );
Run Code Online (Sandbox Code Playgroud)

但如果有一个FloatNear直接使用内置函数的解决方案,那就更简洁了。

  • 注意:Pointwise 位于测试命名空间 `::testing::Pointwise` 中 (2认同)