【问题标题】:Custom EXPECT_NEAR macro in Google TestGoogle 测试中的自定义 EXPECT_NEAR 宏
【发布时间】:2011-08-19 11:13:19
【问题描述】:
范围:使用 Google 测试和 OpenCV。
我想测试我的Vec3f 是否等于另一个Vec3f。 Vec3f 是 OpenCV 中的一个向量,维度为 3,类型为浮点数。 ==-运算符已定义,因此EXPECT_EQ(Vec3f(), Vec3f()) 有效。
但由于它们是浮点数,我想使用 EXPECT_NEAR(float a, float b, float delta) 宏。我该怎么做才能像EXPECT_NEAR(vec_a, vec_b, float delta) 一样使用它?
目前我正在遍历向量的每个元素并在那里执行 EXPECT_NEAR。
这可能是相关的:Convenient method in GoogleTest for a double comparison of not equal?
【问题讨论】:
标签:
unit-testing
macros
opencv
googletest
【解决方案1】:
您可以使用来自 Google Mock 的 Pointwise() 匹配器。将它与检查两个参数是否接近的自定义匹配器结合起来:
#include <tr1/tuple>
#include <gmock/gmock.h>
using std::tr1::get;
using testing::Pointwise;
MATCHER_P(NearWithPrecision, precision, "") {
return abs(get<0>(arg) - get<1>(arg)) < precision;
}
TEST(FooTest, ArraysNear) {
EXPECT_THAT(result_array, Pointwise(NearWithPrecision(0.1), expected_array));
}
【解决方案2】:
你做的基本上是正确的。但是,我会使用自定义断言函数,例如:
::testing::AssertionResult AreAllElementsInVectorNear(const Vec3f& a, const Vect3f& b, float delta) {
if ([MAGIC])
return ::testing::AssertionSuccess();
else
return ::testing::AssertionFailure() << "Vectors differ by more than " << delta;
}
MAGIC 然后会将您的代码包含到例如比较两个向量是否具有相同的大小,然后遍历所有元素并相互检查相同索引处的元素是否相差不超过 delta。请注意,代码假定为 Vec3f 提供了
然后使用该函数:
EXPECT_TRUE(AreAllElementsInVectorNear(a, b, 0.1))
如果期望失败,输出可能是:
Value of: AreAllElementsInVectorNear(a, b, 0.1)
Actual: false (Vectors differ by more then 0.1)
Expected: true