c++vectorgoogletest

Testing Map<int, vector> with Google Test


These are in the Game header file of my class: Order is another class.

std::map<int, std::vector<Order>> ordersToBeExecuted;
std::map<int, std::vector<Order>> getOrdersToBeExecuted();

and this is the definition in my cpp file:

std::map<int, std::vector<Order>> Game::getOrdersToBeExecuted()
{
    return this->ordersToBeExecuted;
}

Now, I don't know how to test this. I am trying Google Tests. I am writing this but currently, I get an error that:

#define EXPECT_EQ(val1,val2) EXPECT_PRED_FORMAT2(::testing::internal:: EqHelper<GTEST_IS_NULL_LITERAL_(val1)>::Compare, val1, val2)
Expands to:

EXPECT_PRED_FORMAT2(::testing::internal:: EqHelper<GTEST_IS_NULL_LITERAL_(std::map<0)>::Compare, std::map<0, std::vector<<Order>>)
expected a type specifier

TEST(gameTest, getOrdersToBeExecutedTest) {

    std::map<int, std::vector<Order>> first;
    std::vector<Order> orders;
    Game g;
    Order o1;
    Order o2;
    orders.push_back(o1);
    orders.push_back(o2);
    first[0] = orders;
    g.setNumberOfPlayers(1);

    EXPECT_EQ(std::map<0,std::vector<Order>>, g.getOrdersToBeExecuted());
}

Edit:

TEST(gameTest, getOrdersToBeExecutedTest) {

    std::map<int, std::vector<Order>> first;
    std::vector<Order> orders;
    std::vector<Order> orders2;
    Game g;
    Order o1, o2;
    Order o3, o4;
    orders.push_back(o1);
    orders.push_back(o2);
    orders2.push_back(o3);
    orders2.push_back(o4);
    first[0] = orders;
    first[1] = orders2;
    //EXPECT_EQ(first, g.getOrdersToBeExecuted());


EXPECT_THAT(g.getOrdersToBeExecuted()), ElementsAre(Pair(0, ElementsAre(o1, o2)), Pair(1, ElementsAre(o3, o4)));
}

I am trying to use but I still get these errors:

#define EXPECT_THAT(value,matcher) EXPECT_PRED_FORMAT1( ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
Expands to:

EXPECT_PRED_FORMAT1( ::testing::internal::MakePredicateFormatterFromMatcher(), g.getOrdersToBeExecuted())
identifier "EXPECT_THAT" is undefined

Solution

  • To test containers use container matchers, see: https://google.github.io/googletest/reference/matchers.html#container-matchers

    Map is a bit tricky, because it's a container of pairs, so you have to combine it with Pair matcher, for example:

    using testing::ElementsAre;
    using testing::Pair;
    
    EXPECT_THAT(g.getOrdersToBeExecuted(), ElementsAre(Pair(key1, val1), Pair(key1, val2)));
    

    When the map's mapped_type is vector you need to use yet another container matcher as second argument for the Pair matcher:

    using testing::ElementsAre;
    using testing::Pair;
    
    EXPECT_THAT(g.getOrdersToBeExecuted(), ElementsAre(Pair(key1, ElementsAre(e1, e2, e3)), Pair(key1, ElementsAre(e4, e5)));