Search code examples
googletest

Combining Pointwise & UnorderedElementsAreArray


I have two arrays of pointers, and I want to use gtest/gmock to assert that they contain the same content, possibly in different order. I tried things like

vector<unique_ptr<int>> a;
vector<unique_ptr<int>> b;

a.push_back(make_unique<int>(42));
a.push_back(make_unique<int>(142));

b.push_back(make_unique<int>(142));
b.push_back(make_unique<int>(42));

// I want this to compile & pass
ASSERT_THAT(a, Pointwise(UnorderedElementsAreArray(), b));

But that didn't work.


Solution

  • Gmock does not provide directly what you want. The problem is that as your arrays contain pointers, you cannot compare their elements directly and have to use matchers for that. You can construct an array of matchers from one of your source arrays, but that will not make things simpler for you.

    But you have some options, depending on what your actual needs are. If you have two arrays and need is to compare whether they the same after sorting, just sort the arrays:

    auto sorted_a = std::sort(a.begin(), a.end(), [](auto x, auto y) {
      return *x < *y;
    });
    auto sorted_b = std::sort(b.begin(), b.end(), [](auto x, auto y) {
      return *x < *y;
    });
    

    and then define a helper matcher and compare them using it:

    MATCHER(PointeesAreEqual, "") {
      return *std::get<0>(arg) == *std::get<1>(arg);
    }
    EXPECT_THAT(a, Pointwise(PointeesAreEqual, b))
    

    But if you simply want to check that an array consists of certain elements, in an arbitrary order, you can write something like this:

    EXPECT_THAT(a, UnorderedElementsAre(Pointee(42), Pointee(142));