unit-testingtestingautomated-testsgooglemock

How to inspect argument to a gmock EXPECT_CALL()?


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()?


Solution

  • 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.