Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock method with optional parameter in Google Mock?

How to mock a method with optional parameter in Google Mock? For example:

class A
{ 
public:
    void set_enable( bool enabled = true );
};

class MockA : public A
{
    MOCK_METHOD1( set_enable, void( bool ) );    // this is not working
};
like image 818
nyarlathotep108 Avatar asked Jul 21 '16 09:07

nyarlathotep108


People also ask

What is Gtest and Gmock?

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.

What is expect call in Gmock?

EXPECT_CALL sets expectation on a mock calls. Writing EXPECT_CALL(mock, methodX(_)). WillRepeatedly(do_action); tells gMock that methodX may be called on mock any number of times with any arguments, and when it is, mock will perform do_action .

What is mocking in Gtest?

Mocking is a process used in unit testing when the unit being tested has external dependencies. The purpose of mocking is to isolate and focus on the code being tested and not on the behavior or state of external dependencies.


2 Answers

This is an alternative of Marko's answer: If you don't want to change your original code, just implement the helper in the mock class:

class A
{ 
public:
    virtual void set_enable( bool enabled = true );
};

class MockA : public A
{
    MOCK_METHOD1( set_enable_impl, void( bool ) );
    virtual void set_enable( bool enabled = true )
    {
        set_enable_impl( enabled );
    }
};

You still have to expect calls of set_enable_impl in your tests, for example

MockA mockA;
EXPECT_CALL(mockA, set_enable_impl(true)).Times(Exactly(1));
EXPECT_CALL(mockA, set_enable_impl(false)).Times(Exactly(1));
like image 65
PiQuer Avatar answered Sep 23 '22 09:09

PiQuer


Change implementation of your method set_enable to use a helper method, like this:

void set_enable( bool enabled = true ) { set_enable_impl(enabled); }

Now, in class MockA, create a mock method for set_enable_impl:

MOCK_METHOD1( set_enable_impl, void( bool ) );

Then, in your production code you simply use set_enable as you would in the first place, while in tests you can set expectations on method set_enable_impl:

MockA mockA;
EXPECT_CALL(mockA, set_enable_impl(_))...;

An alternative would be to overload the method by having versions with one and zero parameters. It is up to you to determine which way works better for your case.

like image 28
Marko Popovic Avatar answered Sep 19 '22 09:09

Marko Popovic