Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 868
Chimera Avatar asked Jan 19 '16 19:01

Chimera


People also ask

What is Expect_call?

EXPECT_CALL not only defines the behavior, but also sets an expectation that the method must be called with the given arguments, for the given number of times (and in the given order when you specify the order too).

How do you mock in Gmock?

first, you use some simple macros to describe the interface you want to mock, and they will expand to the implementation of your mock class; next, you create some mock objects and specify its expectations and behavior using an intuitive syntax; then you exercise code that uses the mock objects.

What is Googlemock?

Gtest is a framework for unit testing. Gmock is a framework imitating the rest of your system during unit tests. Follow this answer to receive notifications.


1 Answers

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.

like image 51
pticawr Avatar answered Oct 10 '22 16:10

pticawr