Google Mock: Mock private variable member that is instantiated in target class's constructor

不问归期 提交于 2019-12-24 08:33:51

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/44916123/google-mock-mock-private-variable-member-that-is-instantiated-in-target-classs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!