How to inspect argument to a gmock EXPECT_CALL()?
Asked Answered
M

1

19

I'm using Google Mock (gMock) for the first time. Given the following code snippet:

class LinkSignals
{
    public:
        virtual ~LinkSignals() { }

        virtual void onLink(std::string) = 0;
        virtual void onUnLink() = 0;
};


class MockLinkSignals : public LinkSignals
{
    public:
        MOCK_METHOD1(onLink, void(std::string));
        MOCK_METHOD0(onUnLink, void());
};

MockLinkSignals mock_signals;

When I execute some test code that causes EXPECT_CALL(mock_signals, onLink(_)) to be run how can I inspect the argument to onLink()?

Middlebrooks answered 19/1, 2016 at 19:59 Comment(0)
O
36

You would normally use either existing gmock matchers or define your own to check the arguments passed to the mock method.

For example, using the default Eq equality matcher:

EXPECT_CALL(mock_signals, onLink("value_I_expect"))

Or check for sub string say:

EXPECT_CALL(mock_signals, onLink(HasSubstr("contains_this")))

The gmock documentation provides details of the standard matchers that are available, and also describes how to make custom matchers, for example for an integer argument type:

MATCHER(IsEven, "") { return (arg % 2) == 0; }

It is possible to capture an argument to a variable by attaching an action to the expectation, although this can have limited use in the scope of the expectation:

EXPECT_CALL(mock_signals, onLink(_)).WillOnce(SaveArg<0>(pointer))

I'd suggest studying the various matchers and actions available before choosing the best approach for your particular case.

Otila answered 19/1, 2016 at 20:15 Comment(2)
In this explanation what is pointer and what is SaveArg<0>(pointer)?Verdaverdant
@Verdaverdant pointer is a pointer to the variable where the argument should be written to, e.g. &myvariable as destination for value of SaveArg<0>Isotonic

© 2022 - 2024 — McMap. All rights reserved.