2

My question is the same as Mockito: Mock private field initialization but for Google Mock framework. In a nutshell:

class Target {
private:
    Person person = new Person();

public:
    void testMethod() {
        person.someMethod();
    }
};

How can I mock the person instance while making unit tests for Target class?

GhostCat
  • 137,827
  • 25
  • 176
  • 248
duong_dajgja
  • 4,196
  • 1
  • 38
  • 65

1 Answers1

3

A non-answer here: simply don't do it this way.

Your problem is the call to new here. Thing is: that makes testing hard, and it also creates a very tight coupling between the Target and the Person class.

The default alternative is: provide a factory to the Target class that creates Person objects for you.

By going for that solution, you

  • avoid to need to mock the call to new
  • you end up with a better design!

And unless I am misreading the documentation, mocking calls to new isn't possible with C++ mocking anyway.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
  • Yeah, I see what you are gonna say. But I am working on adding unit tests for an in-production project and I am ending up using a lot of preprocessor directives to workaround this kind of issues :( – duong_dajgja Jul 05 '17 at 07:38
  • Could you please give me some advice with [this](https://stackoverflow.com/questions/44994780/unit-testing-am-i-doing-right-when-using-another-method-in-unit-testing-a-metho) – duong_dajgja Jul 09 '17 at 11:14