سؤال

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

هل كانت مفيدة؟

المحلول

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

Edit after request from @Blackhex

Suppose our mocked class' constructor takes a reference to some other class it needs:

class helper2 {};
class helper {
public:
  helper(helper2&) {}

  /* Whatever */
};

class base2 {
public:
  base2(helper &h) {}

  virtual int foo(int);
};

Contrary to what I said in the comment, we do need to deal with all the helpers, unfortunately. However, that isn't too painful in this case as we do not need any of their functionality. We build simple, empty "plug" classes:

struct helper2_plug: public helper2 {};
struct helper_plug : public helper {
    helper_plug() : helper(helper2_plug()) {}
};

Then, we can build the mock:

class base2_mock : public base2 {
public:
    base2_mock() : base2(helper_plug()) {}

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

I used struct in my plugs just to avoid the public.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top