生产代码中有很多类方法是非虚的,而为了在Gtest中解除这些非必需的依赖,可以通过Gmock的mock non-virtual methods using templates方法来达到目的。
在此之前,需要了解一种设计模式:Dependency Injection,依赖注入。虽然这个概念始于Java和.net,但在面向对象编程中,C++代码同样应该遵循。

Ps:软件工程中的一个重要的理念就是关注分离(Separation of concern, SoC)。依赖注入不是目的,它是一系列工具和手段,最终的目的是帮助我们开发出松散耦合(loose coupled)、可维护、可测试的代码和程序。这条原则的做法是大家熟知的面向接口,或者说是面向抽象编程。

如何重构代码达到DI的目的呢,下面是一个例子。
原代码:

class A{
public:
  int Funtion1(B& obj) {
    //do something
    std::string str = “mock non-virtual methods using templates”;
     auto rst = obj.Function2(str);
    //do something
  }
}
class B{
public:
int Funtion2(std::string _str){ puts(_str.c_str()); }
}

当我们对类A的方法Function1进行UT防护的时候,不关心其中类B的方法Function2的执行结果,这时候该如何对其进行mock呢(Function2是非虚的)?

在以上这种代码结构中,答案是无法进行mock!除非把Function2修改为virtual或者使用下面的方法:
修改后:

emplate <class T1 >
class RefactorA{
public:
  int Funtion1(T1 & obj) {
    //do something
    std::string str = “mock non-virtual methods using templates”;
    auto rst = obj.Function2(str);
    //do something
  }
}

重构之后,类RefactorA变成了类模板,在实例化的时候把依赖的类B显式的“注入”进去,这时候进行UT的时候,就可以把“注入”的类B的方法Function2 进行mock,代码如下:
//对类B中的Function2进行mock

class  mockB
{
public:
  MOCK_METHOD1(Funtion2, int (std::string ));
};

/对类A进行UT测试

class RefactorA _UT : public :: testing::Test
{
protected:
  virtual void SetUp(){}
  virtual void TearDown(){}   RefactorA < mockB > mockObjA;//实例化模板类
}; TEST_F(RefactorA _UT , Funtion1)
{
  //期望类B的方法Function2被调用至少一次,返回值为100,参数为任意字符串
  mockB mockObjB;
  EXPECT_CALL(mockObjB, Funtion2 (_))
  .Times(AtLeast())
  .WillOnce(Return());   auto rst = mockObjA.Function1( mockObjB );//注意这里传入的是mock出来的对象   EXPECT_TRUE( rst );
}

把类B的方法Function2 mock之后,UT的重点就可以放在对Function1的其它分支上了。

重点:将类A改写为类模板之后,在生产代码中,需要使用真正的类B对象来进行模板类的实例化,而在测试代码中,则需要使用mock出来的类B对象进行模板类的实例化。它们之间的无关的,这与mock接口类的虚函数有着本质的区别。

附:

类模板方法的声明和定义有以下4种方法,可以酌情使用:
① 荐做法是方法在定义的时候就进行实现(类RefactorA);
②  再者是,声明在模板类中,实现在模板类外,但要在一个文件中;
③  把方法的实现写入xxx.inl文件,然后在模板类的结尾使用#include “xxx.inl”;
④  把方法的实现写入xxx.cpp文件,但在cpp文件的最开始需要将模板类实例化。

总之,为了写出可UT的代码,需要时刻牢记“依赖注入”这个原则。
欢迎讨论。

mock non-virtual methods的更多相关文章

  1. What’s wrong with virtual methods called through an interface

    May 31, 2016 Calling a virtual method through an interface always was a lot slower than calling a st ...

  2. why do we need virtual methods in C++?

    http://stackoverflow.com/questions/2391679/why-do-we-need-virtual-methods-in-c Basic idea: when mark ...

  3. 【转载】#349 - The Difference Between Virtual and Non-Virtual Methods

    In C#, virtual methods support polymorphism, by using a combination of the virtual and override keyw ...

  4. Rhino Mock

    mock interfaces, delegates and classes, including those with parameterized constructors. set expecta ...

  5. [转载] google mock cookbook

    原文: https://code.google.com/p/googlemock/wiki/CookBook Creating Mock Classes Mocking Private or Prot ...

  6. CLR via C# 3rd - 08 - Methods

       Kinds of methods        Constructors      Type constructors      Overload operators      Type con ...

  7. 8.Methods(一)

    1.Instance Constructors and Classes (Reference Types) Constructors methods : 1.allow an instance of ...

  8. (转) Virtual function

    原文地址:http://en.wikipedia.org/wiki/Virtual_function In object-oriented programming, a virtual functio ...

  9. Should I expose asynchronous wrappers for synchronous methods?

    Lately I've received several questions along the lines of the following, which I typically summarize ...

  10. why pure virtual function has definition 为什么可以在基类中实现纯虚函数

    看了会音频,无意搜到一个frameworks/base/include/utils/Flattenable.h : virtual ~Flattenable() = 0; 所以查了下“纯虚函数定义实现 ...

随机推荐

  1. (转)基于MVC4+EasyUI的Web开发框架经验总结(7)--实现省份、城市、行政区三者联动

    http://www.cnblogs.com/wuhuacong/p/3841338.html 为了提高客户体验和进行一些技术探索,现在正准备把我自己的客户关系管理系统CRM在做一个Web的版本,因此 ...

  2. Pycharm 设置

    1:显示行号 打上对勾OK 2:设置作者 & 文件编码 3:选择切换Python的版本

  3. springboot版本控制

    HandlerMapping通过继承InitializingBean接口在完成实例后,扫描所有的Controller和标识RequestMapping的方法,缓存这个映射对应关系.然后在应用运行的时候 ...

  4. 4056 hdu4866 Shooting

    题目描述 In the shooting game, the player can choose to stand in the position of [1, X] to shoot, you ca ...

  5. C++基础 (2) 第二天 C++相对C的改进 命名空间 引用

    1 昨日回顾 2内联函数 3 默认参数和占位参数 4函数重载 函数重载 就是可以定义多个相同名字的函数 6 类和对象的基本语法 7 类的封装和访问控制 还有一个结论: 封装有两层含义: 把属性和方法进 ...

  6. mplayer configure选项中文注释

    mplayer configure选项中文注释(MPlayer-1.0rc2) http://blogold.chinaunix.net/u3/104581/showart_2322466.html ...

  7. Java工具类使用注意事项

    (以下摘自阿里巴巴Java开发手册) 1. [强制]获取单例对象需要保证线程安全,其中的方法也要保证线程安全. 说明:资源驱动类.工具类.单例工厂类都需要注意. 5. [强制]SimpleDateFo ...

  8. socket 客户端的认证

    一:使用 hashlib 进行加密验证: # server.py 服务端 import os import socket import hashlib ​ def check_conn(conn): ...

  9. 使用maven服务器插件 运行项目

    使用jetty插件  部署运行 创建一个maven项目:去Maven仓库中寻找jetty插件  然后复制到pom.xml中 使用命令  运行程序: 然后控制台打印: 通过浏览器   访问: ----- ...

  10. SSH框架整合截图总结(三)

    联系人信息查询1 点击 联系人信息查询 超链接时候,到查询页面 (1)在查询页面中,选择客户,根据客户进行查询 下拉表框显示所有客户  可以根据所属的客户进行联系人查询  2 在查询页面中,输入值,提 ...