使用谷歌测试和谷歌模拟比较浮点阵列

时间:2015-02-27 15:17:34

标签: c++ arrays floating-point googletest googlemock

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

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 之内,我希望测试通过。

3 个答案:

答案 0 :(得分:2)

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

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的解决方案,它会更简洁。

答案 1 :(得分:1)

一种方法是使用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);

答案 2 :(得分:1)

以下对我有用:

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

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

其中 testref 属于 std::vector<float> 类型。