How to mock method with optional parameter in Google Mock?

nyarlathotep108 picture nyarlathotep108 · Jul 21, 2016 · Viewed 10.5k times · Source

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
};

Answer

PiQuer picture PiQuer · Jul 12, 2017

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));