Question

I have been trying to find an assertion in the Google C++ Testing Framework / gtest which is equivalent to the BOOST_CHECK_EQUAL_COLLECTIONS assertion found in the Boost Test Library.

However; without success. So my question is two-fold:

  1. Does gtest have an equivalent assertion?
  2. If not: how would one go about asserting container-content in gtest?

EDIT (slightly modified answer):

#include <iostream>

template<typename LeftIter, typename RightIter>
::testing::AssertionResult CheckEqualCollections(LeftIter left_begin,
                                                 LeftIter left_end,
                                                 RightIter right_begin)
{
    std::stringstream message;
    std::size_t index(0);
    bool equal(true);

    for(;left_begin != left_end; left_begin++, right_begin++) {
        if (*left_begin != *right_begin) {
            equal = false;
            message << "\n  Mismatch in position " << index << ": " << *left_begin << " != " <<  *right_begin;
        }
        ++index;
    }
    if (message.str().size()) {
        message << "\n";
    }
    return equal ? ::testing::AssertionSuccess() :
                   ::testing::AssertionFailure() << message.str();
}
Was it helpful?

Solution 2

I don't know of an exactly equivalent gtest assertion. However, the following function should provide similar functionality:

template<typename LeftIter, typename RightIter>
::testing::AssertionResult CheckEqualCollections(LeftIter left_begin,
                                                 LeftIter left_end,
                                                 RightIter right_begin) {
  bool equal(true);
  std::string message;
  std::size_t index(0);
  while (left_begin != left_end) {
    if (*left_begin++ != *right_begin++) {
      equal = false;
      message += "\n\tMismatch at index " + std::to_string(index);
    }
    ++index;
  }
  if (message.size())
    message += "\n\t";
  return equal ? ::testing::AssertionSuccess() :
                 ::testing::AssertionFailure() << message;
}

The section on using a function that returns an AssertionResult gives full details on how to use this, but it would be something like:

EXPECT_TRUE(CheckEqualCollections(collection1.begin(),
                                  collection1.end(),
                                  collection2.begin()));

OTHER TIPS

As Alex has noted, gtest has a sister project called Google Mock, which has excellent facilities for comparing two containers:

EXPECT_THAT(actual, ContainerEq(expected));
// ElementsAre accepts up to ten parameters.
EXPECT_THAT(actual, ElementsAre(a, b, c));
EXPECT_THAT(actual, ElementsAreArray(array));

You'll find more info at Google Mock's wiki .

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top