ekchom
ekchom

Reputation: 148

gtest expected args in mock method

I have mocked a function which takes std::set (stl) as an argument and I expected it to be called with the right args. std::set is a set of user-defined struct and I just want to verify one field of that struct to have one value for all the member of the set. ie

  struct my_struct {
    int i;
    int j;
    int k;
}   
using my_set = std::set<my_struct>;
MOCK_METHOD(void, my_func, (my_set));

EXPECT_CALL(obj, my_func(_))
    .Times(1);
 

Now I want to expect my_func to be called with my_set and each member of my_set is my_struct and my_struct.i should be 1 for all the members.

I understand it could be done with Matcher and Each but now sure how to do that as I run into compilation error

Upvotes: 2

Views: 1182

Answers (1)

Quarra
Quarra

Reputation: 2695

The key is to use ::testing::Each matcher with ::testing::Field matcher combined. Each iterates over all elements of the container argument and Field matcher allows you to set proper expectations on the user-defined struct fields. Complete example:

struct my_struct {
    int i;
    int j;
    int k;
};

auto my_set_comp = [](const auto& l, const auto& r) { return std::tie(l.i, l.j, l.k) < std::tie(r.i, r.j, r.k); };
using my_set = std::set<my_struct, decltype(my_set_comp)>;

class MockClass {
public:
    MOCK_METHOD(void, my_func, (my_set));
};

TEST(SetTest, test1) {
    MockClass obj{};

    my_set a_set{my_set_comp};
    a_set.emplace(my_struct{1, 1, 1});
    a_set.emplace(my_struct{1, 2, 2});
    a_set.emplace(my_struct{1, 3, 3});

    EXPECT_CALL(obj, my_func(::testing::Each(::testing::Field(&my_struct::i, 1)))).Times(1);

    obj.my_func(a_set);
}

or here.

Upvotes: 2

Related Questions