Google测试中的自定义EXPECT_NEAR宏 [英] Custom EXPECT_NEAR macro in Google Test
问题描述
范围:使用Google Test和OpenCV.
Scope: Using Google Test and OpenCV.
我想测试我的Vec3f
等于另一个Vec3f
. Vec3f
是OpenCV中尺寸为3的向量,类型为float.定义了==运算符,因此EXPECT_EQ(Vec3f(), Vec3f())
起作用.
I'd like to test that my Vec3f
equals another Vec3f
. Vec3f
is a vector in OpenCV of dimension 3 and type float. The ==-operator is defined, so EXPECT_EQ(Vec3f(), Vec3f())
works.
但是由于它们是浮点数,所以我想使用EXPECT_NEAR(float a, float b, float delta)
宏.我该怎么做才能像EXPECT_NEAR(vec_a, vec_b, float delta)
一样使用它?
But as they are floats, I'd like to use the EXPECT_NEAR(float a, float b, float delta)
macro. What can I do so that I can use it like EXPECT_NEAR(vec_a, vec_b, float delta)
?
此刻,我正在遍历向量的每个元素,并在那里执行EXPECT_NEAR.
At the moment I am looping through each element of the vector and doing an EXPECT_NEAR there.
这可能与以下内容有关:方便的方法在GoogleTest中进行不相等的双重比较?
This might be related: Convenient method in GoogleTest for a double comparison of not equal?
推荐答案
您所做的基本上是正确的事情.但是,我将使用自定义断言函数,例如:
You are doing basically the correct thing. However, I would use a custom assertion function like:
::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会将您的代码添加到例如比较两个向量的大小是否相同,然后对所有元素进行迭代,并相互检查索引相同的元素的差值是否不超过差值.注意,该代码假定<<为Vec3f提供了运算符.
MAGIC would then include your code to e.g. compare if both vectors have the same size, followed by iterating over all elements and mutually check if the elements at the same index differ by no more than the delta. Note that the code assumes that the << operator is provided for Vec3f.
然后使用该函数:
EXPECT_TRUE(AreAllElementsInVectorNear(a, b, 0.1))
如果期望失败,则输出可能是:
If the expect fails the output might be:
Value of: AreAllElementsInVectorNear(a, b, 0.1)
Actual: false (Vectors differ by more then 0.1)
Expected: true
这篇关于Google测试中的自定义EXPECT_NEAR宏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!