18

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

1 Answer 1

37

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.

4
  • 9
    We do this all the time and there never was a problem. Could you elaborate what the problem is exactly? What have you tried? Does it compile? What are the error messages?
    – arne
    Jul 4, 2013 at 13:15
  • When the mocked class has constructor dependencies passed by reference that have other dependencies and so on, it leads to an explosion of mocks that are irrelevant to the tested case.
    – Blackhex
    Sep 21, 2021 at 10:16
  • @Blackhex Not really. You'd have to mock the classes that are immediately passed into the constructor, not the whole cascade.
    – arne
    Sep 21, 2021 at 12:31
  • That's awesome news. Can you point us to some example of how to do it, please? You can add is as an answer to this post, I'd certainly upvote it.
    – Blackhex
    Sep 21, 2021 at 22:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.