Mocking Parametrized Constructor using Gmock

Daemon picture Daemon · Jul 4, 2013 · Viewed 21k times · Source

I have class to be mocked but it does not have a default constructor. I cannot change the source code, so is there any way to mock a parametrized constructor using Gmock

Answer

arne picture arne · Jul 4, 2013

Yes there is. Just let your Mock's constructor call the mocked class' constructor with the right arguments:

class base_class {
public:
    base_class(int, int) {}

    virtual int foo(int);
};


class base_mock : public base_class {
public:
    base_mock() : base_class(23, 42) {}

    MOCK_METHOD1(foo, int(int));
};

or even

class base_mock : public base_class {
public:
    base_mock(int a, int b) : base_class(a, b) {}

    MOCK_METHOD1(foo, int(int));
};