Mocking Parametrized Constructor using Gmock

2019-06-18 05:33发布

问题:

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

回答1:

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