使用Google Test和Google Mock进行浮点数数组的比较

6

我是Google测试产品的新手,正在使用一些信号处理代码尝试它们。我试图使用Google Mock来断言两个浮点数数组在某个范围内相等,正如这个问题的答案所建议的那样。我想知道向以下表达式添加一些误差容忍度的推荐方法...

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
}) )  );

如果数组中元素的值相差不超过10-8,我希望测试通过。


如果不需要,可以回滚指数。顺便问一下,你的容差背后的科学原理是什么? - Bathsheba
3个回答

8
以下对我有效:
using ::testing::Pointwise;
using ::testing::FloatNear;

auto const max_abs_error = 1 / 1024.f;
ASSERT_THAT(
    test,
    Pointwise(FloatNear(max_abs_error), ref));

testrefstd::vector<float>类型。


4

一种方法是使用googletest而不是googlemock宏,这将导致更紧凑的断言:

#define EXPECT_FLOATS_NEARLY_EQ(expected, actual, thresh) \
        EXPECT_EQ(expected.size(), actual.size()) << "Array sizes differ.";\
        for (size_t idx = 0; idx < std::min(expected.size(), actual.size()); ++idx) \
        { \
            EXPECT_NEAR(expected[idx], actual[idx], thresh) << "at index: " << idx;\
        }

// define expected_array as in the other answer
EXPECT_FLOATS_NEARLY_EQ(impulse, expected_array, 0.001);

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) ;
}

然后可以在测试中与Pointwise一起使用。
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  ) );

但如果有一种直接使用内置的FloatNear的解决方案,那就更好了。


2
注意:Pointwise 在测试命名空间 ::testing::Pointwise 中。 - fgiraldeau
1
提示:传递给 MATCHER_P 的字符串应该描述匹配器的“通过”标准,而不是其失败标准。 - Rufus

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接