Custom EXPECT_NEAR macro in Google Test

跟風遠走 提交于 2019-12-05 19:04:25

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 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.

The function then is used:

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

You can use the Pointwise() matcher from Google Mock. Combine it with a custom matcher that checks that the two arguments are near:

#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));
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!