Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Check if element equality for different container types in Google Test

I want to check if the elements in two containers of different types are the same. However, when I use the ContainerEq matcher of the GoogleTest library it gives me an error that it can not initialize the vector from the array:

TEST(TestExample, Example) {
    std::array<int, 4> ar = {1,2,3,4};
    std::vector<int> v(ar.begin(), ar.end());

    EXPECT_THAT(ar, ::testing::ContainerEq(v));
}

Error message:

error: invalid initialization of reference of type 'testing::internal::ContainerEqMatcher<std::vector<int> >::StlContainerReference' {aka 'const std::vector<int>&'} from expression of type 'const type' {aka 'const std::array<int, 4>'}

What options do I have to check for equality in different containers except for switching to EXPECT_TRUE and using std::equal?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can compare elements of different containers using ::testing::ElementsAreArray(v):

TEST(TestExample, Example) {
    std::array<int, 4> ar = {1,2,3,4};
    std::vector<int> v(ar.begin(), ar.end());

    EXPECT_THAT(ar, ::testing::ElementsAreArray(v));
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading