Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom EXPECT_NEAR macro in Google Test

Scope: Using Google Test and OpenCV.

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.

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)?

At the moment I am looping through each element of the vector and doing an EXPECT_NEAR there.

This might be related: Convenient method in GoogleTest for a double comparison of not equal?

like image 978
Unapiedra Avatar asked Aug 19 '11 11:08

Unapiedra


People also ask

How do I run a Gtest disabled test?

If you know a test will fail before running it, then you can disable it temporarily by prepending DISABLED_ to the test name.

Does gMock include Gtest?

gMock is bundled with googletest.

How do you write a value parameterized test?

How to Write Value-Parameterized Tests. To write value-parameterized tests, first you should define a fixture class. It must be derived from both testing::Test and testing::WithParamInterface<T> (the latter is a pure interface), where T is the type of your parameter values.


2 Answers

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));
}
like image 52
VladLosev Avatar answered Nov 12 '22 02:11

VladLosev


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
like image 39
dmeister Avatar answered Nov 12 '22 02:11

dmeister