Google Mock:模拟私有变量成员,该成员在目标类的构造函数中实例化 [英] Google Mock: Mock private variable member that is instantiated in target class's constructor

查看:421
本文介绍了Google Mock:模拟私有变量成员,该成员在目标类的构造函数中实例化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题与 Mockito:模拟私有字段初始化相同,但针对Google模拟框架.简而言之:

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

在为Target类进行单元测试时,如何模拟person实例?

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

推荐答案

此处没有答案:根本不要这样做.

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

您的问题是在这里致电new.事实是:这使得测试变得困难,并且还在TargetPerson类之间建立了非常紧密的联系.

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.

默认的替代方法是:为Target类提供一个 factory ,该类为您创建Person对象.

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

寻求该解决方案,您

  • 避免需要模拟对new
  • 的调用
  • 您最终将获得更好的设计!
  • avoid to need to mock the call to new
  • you end up with a better design!

除非我误读了文档 ,无论如何用C ++模拟都无法模拟对new的调用.

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

这篇关于Google Mock:模拟私有变量成员,该成员在目标类的构造函数中实例化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆