生产代码中有很多类方法是非虚的,而为了在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. Q1002 四则运算

    #include<iostream> using namespace std; int main() { long long sum1,sum2,sum3,sum4; long int a ...

  2. input输入值限制

    限制输入框只能输入数字并且保留两位小数 <input type= "text" onkeyup="var p2 = parseFloat(value).toFixe ...

  3. Spring中xml文档的schema约束

    最开始使用Spring框架的时候,对于其配置文件xml,只是网上得知其使用方法,而不明其意.最近想着寻根问底的探究一下.以下是本文主要内容: 1.配置文件示例.   <?xml version= ...

  4. Javaee 方法的格式和注意事项

    1.构造方法的格式是什么?有哪些注意事项?   修饰符+方法名称+(参数列表),构造的方法没有返回值,方法名称要和类名一样,有属性参数的需要在成员变量前加this,参数列表的值要和指定的方法格式相同. ...

  5. Camera三维动画

    一.概述 在Android中说到3D开发,我们首先想到的是OpenGL,但用起来比较复杂繁琐,不适合做应用级别的3D变换.Android为我们提供了一个简化版的3D开发入口:Camera(这里的Cam ...

  6. nyoj329-循环小数

    329-循环小数 内存限制:64MB时间限制:3000msSpecial Judge: No accepted:1submit:1 题目描述: 我们可爱的 c小加 近段儿正在潜心研究数学,当他学习到循 ...

  7. nlogn求逆序对&&陌上花开

    前置: nlogn逆序对: 前一个小时我还真的不会这个Orz 这里运用归并排序的思想. 对于一个序列,我们把它先分开,再合并成一个有序序列. 引自https://blog.csdn.net/qq_30 ...

  8. centos7把编译安装的服务通过systemctl管理

    nginx编译安装的目录是/usr/local/nginx nginx配置文件是/usr/local/nginx/conf/nginx.conf systemctl管理的服务文件在/usr/lib/s ...

  9. 用Js写贪吃蛇

    使用Javascript做贪吃蛇小游戏, 1.自定义地图宽高,蛇的初始速度 2.食物随机出现 3.蛇的样式属性 4.贪吃蛇玩法(吃食物,碰到边界,吃食物后加速,计分,) <!DOCTYPE ht ...

  10. js获取日期当天的开始时间和结束时间

    //函数调用传参格式为 2018-6-6或者2018.6.6//如:startUnix(2018-6-6) 返回的时间戳格式‘1528300799’ function startUnix($date) ...