c++googletestmatcher

Test containment with GoogleTest's Contains matcher?


I'm writing a test and would like to check if some element is contained in a vector. Should be simple and common, so I expected GoogleTest would have some assertion for it. And indeed, it does according to its documentation: http://google.github.io/googletest/reference/matchers.html

In the reference it names a matcher called Contains(e) which is supposed to check if a container contains a certain element. Going by the context I'm assuming it would need to be called like this:

std::vector<int> vec({1, 2, 3, 4});
EXPECT_THAT(vec, ::testing::Contains(3)); //Should pass the test.

However this gives a compilation error:

error: no member named 'Contains' in namespace 'testing'
EXPECT_THAT(vec, ::testing::Contains(3));
                 ~~~~~~~~~~~^

Am I using this wrong? I don't think I've ever worked with these matchers before. However some of the matchers do work correctly, like ::testing::Lt. Or is the documentation of GoogleTest outdated?

I'm using Clang 12, and GoogleTest 1.11.

As a workaround I'm currently simply using std::find and checking for the iterator not being equal to vec.end(), but it's not as semantic as I'd like it to be.


Solution

  • Solution from the comments:

    To use matchers one needs to #include <gmock/gmock.h>.

    Explanation:

    EXPECT_THAT(value, matcher) verifies that value matches matcher (see here) so the second argument has to be a matcher. And those are part of (formerly separate) GMock, hence they are defined in <gmock/gmock-matchers.h> and <gmock/gmock-more-matchers.h> which are included by <gmock/gmock.h>.