google mock C++单元测试框架

 http://blog.chinaunix.net/uid-25748718-id-3129590.htmlhtml

Google Mock 入门概述什么是Mock?正则表达式

Mock,更确切地说应该是Mock Object。它到底是什么?它有什么做用?在这里,我也只能先说说个人理解。 好比当咱们在单元测试、模块的接口测试时,当这个模块须要依赖另一个/几个类,而这时这些个类尚未开发好(那名开发同窗比较懒,呵呵),这时咱们就能够定义了Mock对象来模拟那些类的行为。
说得更直白一些,就是本身实现一个假的依赖类,对这个类的方法你想要什么行为就能够有什么行为,你想让这个方法返回什么结果就能够返回怎么样的结果。
但这时不少同窗每每会提出一个问题:"那既然是我本身实现一个假的依赖类",那和那些市面上的Mock框架有什么关系啊?
这个实际上是这样的,这些个Mock框架能够帮助你比较方便、比较轻松地实现这些个假的依赖类。毕竟,若是你实现这么一个假的依赖类的时间花费过场的话,那我还不如等待那位懒惰的同窗吧。api

Google Mock概述

Google Mock(简称gmock)是Google在2008年推出的一套针对C++的Mock框架,它灵感取自于jMockEasyMockharcreat。它提供了如下这些特性:数组

  • 轻松地建立mock类
  • 支持丰富的匹配器(Matcher)和行为(Action)
  • 支持有序、无序、部分有序的指望行为的定义
  • 多平台的支持
参考文档 Google Mock使用最简单的例子

我比较喜欢举例来讲明这些个、那些个玩意,所以咱们先来看看Google Mock就简单的用法和做用。数据结构

  • 首先,那个懒惰的同窗已经定义好了这么一个接口(万幸,他至少把接口定义好了):

FooInterface.h框架

  1. #ifndef FOOINTERFACE_H_
  2. #define FOOINTERFACE_H_
  3.  
  4. #include 
  5.  
  6. namespace seamless {
  7.  
  8. class FooInterface {
  9. public:
  10.         virtual ~FooInterface() {}
  11.  
  12. public:
  13.         virtual std::string getArbitraryString() = 0;
  14. };
  15.  
  16. }  // namespace seamless
  17.  
  18. #endif // FOOINTERFACE_H_
这里须要注意几点:

 

  • FooInterface的析构函数~FooInterface()必须是virtual的
  • 在第13行,咱们得把getArbitraryString定义为纯虚函数。其实getArbitraryString()也不必定得是纯虚函数,这点咱们后面会提到.

如今咱们用Google Mock来定义Mock类 FooMock.hless

  1. #ifndef MOCKFOO_H_
  2. #define MOCKFOO_H_
  3.  
  4. #include 
  5. #include 
  6. #include "FooInterface.h"
  7.  
  8. namespace seamless {
  9.  
  10. class MockFoo: public FooInterface {
  11. public:
  12.         MOCK_METHOD0(getArbitraryString, std::string());
  13. };
  14.  
  15. }  // namespace seamless
  16.  
  17. #endif // MOCKFOO_H_
咱们稍微来解释一下这个Mock类的定义:

 

  • 第10行咱们的MockFoo类继承懒同窗的FooInterface
  • 第22行咱们定义使用gmock中的一个宏(Macro)MOCK_METHOD0来定义MockFoo中的getArbitraryString。Google Mock是须要你根据不一样的形参个数来使用不一样的Mock Method,我这里getArbitraryString没有函数,就是MOCK_METHOD0了,同理,若是是一个形参,就是MOCK_METHOD1了,以此往下。

FooMain.ccide

  1. #include 
  2. #include 
  3. #include 
  4. #include 
  5. #include 
  6.  
  7. #include "MockFoo.h"
  8.  
  9. using namespace seamless;
  10. using namespace std;
  11.  
  12. using ::testing::Return;
  13.  
  14. int main(int argc, char** argv) {
  15.         ::testing::InitGoogleMock(&argc, argv);
  16.  
  17.         string value = "Hello World!";
  18.         MockFoo mockFoo;
  19.         EXPECT_CALL(mockFoo, getArbitraryString()).Times(1).
  20.                 WillOnce(Return(value));
  21.         string returnValue = mockFoo.getArbitraryString();
  22.         cout << "Returned Value: " << returnValue << endl;
  23.  
  24.         return EXIT_SUCCESS;
  25. }

最后咱们运行编译,获得的结果以下:函数

Returned Value: Hello World!

 

在这里:

 

  • 第15行,初始化一个Google Mock
  • 第18行,声明一个MockFoo的对象:mockFoo
  • 第19行,是为MockFoo的getArbitraryString()方法定义一个指望行为,其中Times(1)的意思是运行一次,WillOnce(Return(value))的意思是第一次运行时把value做为getArbitraryString()方法的返回值。

这就是咱们最简单的使用Google Mock的例子了,使用起来的确比较简便吧。post

典型的流程

经过上述的例子,已经能够看出使用Mock类的通常流程以下:

  • 引入你要用到的Google Mock名称. 除宏或其它特别提到的以外全部Google Mock名称都位于*testing*命名空间之下.
  • 创建模拟对象(Mock Objects).
  • 可选的,设置模拟对象的默认动做.
  • 在模拟对象上设置你的预期(它们怎样被调用,应该怎样回应?).
自定义方法/成员函数的指望行为

从上述的例子中能够看出,当咱们针对懒同窗的接口定义好了Mock类后,在单元测试/主程序中使用这个Mock类中的方法时最关键的就是对指望行为的定义。
对方法指望行为的定义的语法格式以下:

  1. EXPECT_CALL(mock_object, method(matcher1, matcher2, ...))
  2.     .With(multi_argument_matcher)
  3.     .Times(cardinality)
  4.     .InSequence(sequences)
  5.     .After(expectations)
  6.     .WillOnce(action)
  7.     .WillRepeatedly(action)
  8.     .RetiresOnSaturation();
解释一下这些参数(虽然不少我也没弄明白):

 

  • 第1行的mock_object就是你的Mock类的对象
  • 第1行的method(matcher1, matcher2, …)中的method就是你Mock类中的某个方法名,好比上述的getArbitraryString;而matcher(匹配器)的意思是定义方法参数的类型,咱们待会详细介绍。
  • 第3行的Times(cardinality)的意思是以前定义的method运行几回。至于cardinality的定义,我也会在后面详细介绍。
  • 第4行的InSequence(sequences)的意思是定义这个方法被执行顺序(优先级),我会再后面举例说明。
  • 第6行WillOnce(action)是定义一次调用时所产生的行为,好比定义该方法返回怎么样的值等等。
  • 第7行WillRepeatedly(action)的意思是缺省/重复行为。

我稍微先举个例子来讲明一下,后面有针对更为详细的说明:

  1. EXPECT_CALL(mockTurtle, getX()).Times(testing::AtLeast(5)).
  2.                 WillOnce(testing::Return(100)).WillOnce(testing::Return(150)).
  3.                 WillRepeatedly(testing::Return(200))
这个指望行为的定义的意思是:

 

  • 调用mockTurtle的getX()方法
  • 这个方法会至少调用5次
  • 第一次被调用时返回100
  • 第2次被调用时返回150
  • 从第3次被调用开始每次都返回200
Matcher(匹配器)

Matcher用于定义Mock类中的方法的形参的值(固然,若是你的方法不须要形参时,能够保持match为空。),它有如下几种类型:(更详细的介绍能够参见Google Mock Wiki上的Matcher介绍
通配符

_ 能够表明任意类型
A() or An() 能够是type类型的任意值
这里的 _和*A*包括下面的那个匹配符都在Google Mock的* ::testing*这个命名空间下,你们要用时须要先引入那个命名空间

通常比较

Eq(value) 或者 value argument == value,method中的形参必须是value
Ge(value) argument >= value,method中的形参必须大于等于value
Gt(value) argument > value
Le(value) argument <= value
Lt(value) argument < value
Ne(value) argument != value
IsNull() method的形参必须是NULL指针
NotNull() argument is a non-null pointer
Ref(variable) 形参是variable的引用
TypedEq(value) 形参的类型必须是type类型,并且值必须是value

浮点数的比较

DoubleEq(a_double) 形参是一个double类型,好比值近似于a_double,两个NaN是不相等的
FloatEq(a_float) 同上,只不过类型是float
NanSensitiveDoubleEq(a_double) 形参是一个double类型,好比值近似于a_double,两个NaN是相等的,这个是用户所但愿的方式
NanSensitiveFloatEq(a_float) 同上,只不过形参是float

字符串匹配
这里的字符串便可以是C风格的字符串,也能够是C++风格的。

ContainsRegex(string) 形参匹配给定的正则表达式
EndsWith(suffix) 形参以suffix截尾
HasSubstr(string) 形参有string这个子串
MatchesRegex(string) 从第一个字符到最后一个字符都彻底匹配给定的正则表达式.
StartsWith(prefix) 形参以prefix开始
StrCaseEq(string) 参数等于string,而且忽略大小写
StrCaseNe(string) 参数不是string,而且忽略大小写
StrEq(string) 参数等于string
StrNe(string) 参数不等于string

容器的匹配
不少STL的容器的比较都支持==这样的操做,对于这样的容器可使用上述的Eq(container)来比较。但若是你想写得更为灵活,可使用下面的这些容器匹配方法:

Contains(e) 在method的形参中,只要有其中一个元素等于e
Each(e) 参数各个元素都等于e
ElementsAre(e0, e1, …, en) 形参有n+1的元素,而且挨个匹配
ElementsAreArray(array) 或者ElementsAreArray(array, count) 和ElementsAre()相似,除了预期值/匹配器来源于一个C风格数组
ContainerEq(container) 类型Eq(container),就是输出结果有点不同,这里输出结果会带上哪些个元素不被包含在另外一个容器中
Pointwise(m, container)  

上述的一些匹配器都比较简单,我就随便打包举几最简单的例子演示一下吧: 我稍微修改一下以前的Foo.hMockFoo.h, MockFoo.h 增长了2个方法

  1. #ifndef MOCKFOO_H_
  2. #define MOCKFOO_H_
  3.  
  4. #include 
  5. #include 
  6. #include 
  7. #include "FooInterface.h"
  8.  
  9. namespace seamless {
  10.  
  11. class MockFoo: public FooInterface {
  12. public:
  13.         MOCK_METHOD0(getArbitraryString, std::string());
  14.         MOCK_METHOD1(setValue, void(std::string& value));
  15.         MOCK_METHOD2(setDoubleValues, void(int x, int y));
  16. };
  17.  
  18. }  // namespace seamless
  19.  
  20. #endif // MOCKFOO_H_

FooMain.h

  1. #include 
  2. #include 
  3. #include 
  4. #include 
  5.  
  6. #include "MockFoo.h"
  7.  
  8. using namespace seamless;
  9. using namespace std;
  10.  
  11. using ::testing::Assign;
  12. using ::testing::Eq;
  13. using ::testing::Ge;
  14. using ::testing::Return;
  15.  
  16. int main(int argc, char** argv) {
  17.         ::testing::InitGoogleMock(&argc, argv);
  18.  
  19.         string value = "Hello World!";
  20.         MockFoo mockFoo;
  21.  
  22.         EXPECT_CALL(mockFoo, setValue(testing::_));
  23.         mockFoo.setValue(value);
  24.  
  25.         // 这里我故意犯错
  26.         EXPECT_CALL(mockFoo, setDoubleValues(Eq(1), Ge(1)));
  27.         mockFoo.setDoubleValues(1, 0);
  28.  
  29.         return EXIT_SUCCESS;
  30. }
  • 第22行,让setValue的形参能够传入任意参数
  • 另外,我在第26~27行故意犯了个错(为了说明上述这些匹配器的做用),我以前明明让setDoubleValues第二个参数得大于等于1,但我实际传入时却传入一个0。这时程序运行时就报错了:
unknown file: Failure

 

Unexpected mock function call – returning directly.
Function call: setDoubleValues(1, 0)
Google Mock tried the following 1 expectation, but it didn't match:

FooMain.cc:35: EXPECT_CALL(mockFoo, setDoubleValues(Eq(1), Ge(1)))…
Expected arg #1: is >= 1
Actual: 0
Expected: to be called once
Actual: never called – unsatisfied and active
FooMain.cc:35: Failure
Actual function call count doesn't match EXPECT_CALL(mockFoo, setDoubleValues(Eq(1), Ge(1)))…
Expected: to be called once
Actual: never called – unsatisfied and active

上述的那些匹配器都比较简单,下面咱们来看看那些比较复杂的匹配吧。
成员匹配器

Field(&class::field, m) argument.field (或 argument->field, 当argument是一个指针时)与匹配器m匹配, 这里的argument是一个class类的实例.
Key(e) 形参(argument)比较是一个相似map这样的容器,而后argument.first的值等于e
Pair(m1, m2) 形参(argument)必须是一个pair,而且argument.first等于m1,argument.second等于m2.
Property(&class::property, m) argument.property()(或argument->property(),当argument是一个指针时)与匹配器m匹配, 这里的argument是一个class类的实例.

仍是举例说明一下:

  1. TEST(TestField, Simple) {
  2.         MockFoo mockFoo;
  3.         Bar bar;
  4.         EXPECT_CALL(mockFoo, get(Field(&Bar::num, Ge(0)))).Times(1);
  5.         mockFoo.get(bar);
  6. }
  7.  
  8. int main(int argc, char** argv) {
  9.         ::testing::InitGoogleMock(&argc, argv);
  10.         return RUN_ALL_TESTS();
  11. }
这里咱们使用 Google Test来写个测试用例,这样看得比较清楚。

 

  • 第5行,咱们定义了一个Field(&Bar::num, Ge(0)),以说明Bar的成员变量num必须大于等于0。

上面这个是正确的例子,咱们为了说明Field的做用,传入一个bar.num = -1试试。

  1. TEST(TestField, Simple) {
  2.         MockFoo mockFoo;
  3.         Bar bar;
  4.         bar.num = -1;
  5.         EXPECT_CALL(mockFoo, get(Field(&Bar::num, Ge(0)))).Times(1);
  6.         mockFoo.get(bar);
  7. }
运行是出错了:

 

[==========] Running 1 test from 1 test case.
[----------] Global test environment set-up.
[----------] 1 test from TestField
[ RUN ] TestField.Simple
unknown file: Failure

 

Unexpected mock function call – returning directly.
Function call: get(@0xbff335bc 4-byte object )
Google Mock tried the following 1 expectation, but it didn't match:

FooMain.cc:34: EXPECT_CALL(mockFoo, get(Field(&Bar::num, Ge(0))))…
Expected arg #0: is an object whose given field is >= 0
Actual: 4-byte object , whose given field is -1
Expected: to be called once
Actual: never called – unsatisfied and active
FooMain.cc:34: Failure
Actual function call count doesn't match EXPECT_CALL(mockFoo, get(Field(&Bar::num, Ge(0))))…
Expected: to be called once
Actual: never called – unsatisfied and active
[ FAILED ] TestField.Simple (0 ms)
[----------] 1 test from TestField (0 ms total)

[----------] Global test environment tear-down
[==========] 1 test from 1 test case ran. (0 ms total)
[ PASSED ] 0 tests.
[ FAILED ] 1 test, listed below:
[ FAILED ] TestField.Simple

1 FAILED TEST

匹配函数或函数对象的返回值

ResultOf(f, m) f(argument) 与匹配器m匹配, 这里的f是一个函数或函数对象.

指针匹配器

Pointee(m) argument (不管是智能指针仍是原始指针) 指向的值与匹配器m匹配.

复合匹配器

AllOf(m1, m2, …, mn) argument 匹配全部的匹配器m1到mn
AnyOf(m1, m2, …, mn) argument 至少匹配m1到mn中的一个
Not(m) argument 不与匹配器m匹配
  1. EXPECT_CALL(foo, DoThis(AllOf(Gt(5), Ne(10))));
  • 传入的参数必须 >5 而且 <= 10
  1. EXPECT_CALL(foo, DoThat(Not(HasSubstr("blah")), NULL));
  • 第一个参数不包含“blah”这个子串
基数(Cardinalities)

基数用于Times()中来指定模拟函数将被调用多少次|

AnyNumber() 函数能够被调用任意次.
AtLeast(n) 预计至少调用n次.
AtMost(n) 预计至多调用n次.
Between(m, n) 预计调用次数在m和n(包括n)之间.
Exactly(n) 或 n 预计精确调用n次. 特别是, 当n为0时,函数应该永远不被调用.
行为(Actions)

Actions(行为)用于指定Mock类的方法所指望模拟的行为:好比返回什么样的值、对引用、指针赋上怎么样个值,等等。 值的返回

Return() 让Mock方法返回一个void结果
Return(value) 返回值value
ReturnNull() 返回一个NULL指针
ReturnRef(variable) 返回variable的引用.
ReturnPointee(ptr) 返回一个指向ptr的指针

另外一面的做用(Side Effects)

Assign(&variable, value) 将value分配给variable

使用函数或者函数对象(Functor)做为行为

Invoke(f) 使用模拟函数的参数调用f, 这里的f能够是全局/静态函数或函数对象.
Invoke(object_pointer, &class::method) 使用模拟函数的参数调用object_pointer对象的mothod方法.

复合动做

DoAll(a1, a2, …, an) 每次发动时执行a1到an的全部动做.
IgnoreResult(a) 执行动做a并忽略它的返回值. a不能返回void.

这里我举个例子来解释一下DoAll()的做用,我我的认为这个DoAll()仍是挺实用的。例若有一个Mock方法:

  1. virtual int getParamter(std::string* name,  std::string* value) = 0

对于这个方法,我这回须要操做的结果是将name指向value的地址,而且获得方法的返回值。
相似这样的需求,咱们就能够这样定义指望过程:

  1. TEST(SimpleTest, F1) {
  2.     std::string* a = new std::string("yes");
  3.     std::string* b = new std::string("hello");
  4.     MockIParameter mockIParameter;
  5.     EXPECT_CALL(mockIParameter, getParamter(testing::_, testing::_)).Times(1).\
  6.         WillOnce(testing::DoAll(testing::Assign(&a, b), testing::Return(1)));
  7.     mockIParameter.getParamter(a, b);
  8. }
这时就用上了咱们的DoAll()了,它将Assign()和Return()结合起来了。
序列(Sequences)

默认时,对于定义要的指望行为是无序(Unordered)的,即当我定义好了以下的指望行为:

  1.         MockFoo mockFoo;
  2.         EXPECT_CALL(mockFoo, getSize()).WillOnce(Return(1));
  3.         EXPECT_CALL(mockFoo, getValue()).WillOnce(Return(string("Hello World")));
对于这样的指望行为的定义,我什么时候调用 mockFoo.getValue()或者什么时候 mockFoo.getSize()均可以的。

但有时候咱们须要定义有序的(Ordered)的调用方式,即序列 (Sequences) 指定预期的顺序. 在同一序列里的全部预期调用必须按它们指定的顺序发生; 反之则能够是任意顺序.

  1. using ::testing::Return;
  2. using ::testing::Sequence;
  3.  
  4. int main(int argc, char **argv) {
  5.         ::testing::InitGoogleMock(&argc, argv);
  6.  
  7.         Sequence s1, s2;
  8.         MockFoo mockFoo;
  9.         EXPECT_CALL(mockFoo, getSize()).InSequence(s1, s2).WillOnce(Return(1));
  10.         EXPECT_CALL(mockFoo, getValue()).InSequence(s1).WillOnce(Return(
  11.                 string("Hello World!")));
  12.         cout << "First:\t" << mockFoo.getSize() << endl;
  13.         cout << "Second:\t" << mockFoo.getValue() << endl;
  14.  
  15.         return EXIT_SUCCESS;
  16. }
  • 首先在第8行创建两个序列:s一、s2。
  • 而后在第11行中,EXPECT_CALL(mockFoo, getSize()).InSequence(s1, s2)说明getSize()的行为优先于s一、s2.
  • 而第12行时,EXPECT_CALL(mockFoo, getValue()).InSequence(s1)说明getValue()的行为在序列s1中。

获得的结果以下:

First: 1
Second: Hello World!

当我尝试一下把mockFoo.getSize()mockFoo.getValue()的调用对调时试试:

  1.         cout << "Second:\t" << mockFoo.getValue() << endl;
  2.         cout << "First:\t" << mockFoo.getSize() << endl;
获得以下的错误信息:

 

unknown file: Failure

 

Unexpected mock function call – returning default value.
Function call: getValue()
Returns: ""
Google Mock tried the following 1 expectation, but it didn't match:

FooMain.cc:29: EXPECT_CALL(mockFoo, getValue())…
Expected: all pre-requisites are satisfied
Actual: the following immediate pre-requisites are not satisfied:
FooMain.cc:28: pre-requisite #0
(end of pre-requisites)
Expected: to be called once
Actual: never called – unsatisfied and active
Second:
First: 1
FooMain.cc:29: Failure
Actual function call count doesn't match EXPECT_CALL(mockFoo, getValue())…
Expected: to be called once
Actual: never called – unsatisfied and active

另外,咱们还有一个偷懒的方法,就是不要这么傻乎乎地定义这些个Sequence s1, s2的序列,而根据我定义指望行为(EXPECT_CALL)的顺序而自动地识别调用顺序,这种方式可能更为地通用。

  1. using ::testing::InSequence;
  2. using ::testing::Return;
  3.  
  4. int main(int argc, char **argv) {
  5.         ::testing::InitGoogleMock(&argc, argv);
  6.  
  7.         InSequence dummy;
  8.         MockFoo mockFoo;
  9.         EXPECT_CALL(mockFoo, getSize()).WillOnce(Return(1));
  10.         EXPECT_CALL(mockFoo, getValue()).WillOnce(Return(string("Hello World")));
  11.  
  12.         cout << "First:\t" << mockFoo.getSize() << endl;
  13.         cout << "Second:\t" << mockFoo.getValue() << endl;
  14.  
  15.         return EXIT_SUCCESS;
  16. }
Mock实践

下面我从我在工做中参与的项目中选取了一个实际的例子来实践Mock。
这个例子的背景是用于搜索引擎的:

  • 引擎接收一个查询的Query,好比http://127.0.0.1/search?q=mp3&retailwholesale=0&isuse_alipay=1
  • 引擎接收到这个Query后,将解析这个Query,将Query的Segment(如q=mp三、retail_wholesale=0放到一个数据结构中)
  • 引擎会调用另外内部模块具体根据这些Segment来处理相应的业务逻辑。

因为Google Mock不能Mock模版方法,所以我稍微更改了一下本来的接口,以便演示:

我改过的例子

咱们先来看看引擎定义好的接口们:
VariantField.h 一个联合体,用于保存Query中的Segment的值

  1. #ifndef VARIANTFIELD_H_
  2. #define VARIANTFIELD_H_
  3.  
  4. #include <boost/cstdint.hpp>
  5.  
  6. namespace seamless {
  7.  
  8. union VariantField
  9. {
  10.     const char * strVal;
  11.     int32_t intVal;
  12. };
  13.  
  14. }  // namespace mlr_isearch_api
  15.  
  16. #endif // VARIANTFIELD_H_

IParameterInterface.h 提供一个接口,用于获得Query中的各个Segment的值

  1. #ifndef IPARAMETERINTERFACE_H_
  2. #define IPARAMETERINTERFACE_H_
  3.  
  4. #include <boost/cstdint.hpp>
  5.  
  6. #include "VariantField.h"
  7.  
  8. namespace seamless {
  9.  
  10. class IParameterInterface {
  11. public:
  12.         virtual ~IParameterInterface() {};
  13.  
  14. public:
  15.         virtual int32_t getParameter(const char* name,  VariantField*& value) = 0;
  16. };
  17.  
  18. }  // namespace
  19.  
  20. #endif // IPARAMETERINTERFACE_H_

IAPIProviderInterface.h 一个统一的外部接口

  1. #ifndef IAPIPROVIDERINTERFACE_H_
  2. #define IAPIPROVIDERINTERFACE_H_
  3.  
  4. #include <boost/cstdint.hpp>
  5.  
  6. #include "IParameterInterface.h"
  7. #include "VariantField.h"
  8.  
  9. namespace seamless {
  10.  
  11. class IAPIProviderInterface {
  12. public:
  13.         IAPIProviderInterface() {}
  14.         virtual ~IAPIProviderInterface() {}
  15.  
  16. public:
  17.         virtual IParameterInterface* getParameterInterface() = 0;
  18. };
  19.  
  20. }
  21.  
  22. #endif // IAPIPROVIDERINTERFACE_H_

引擎定义好的接口就以上三个,下面是引擎中的一个模块用于根据Query中的Segment接合业务处理的。Rank.h 头文件

  1. #ifndef RANK_H_
  2. #define RANK_H_
  3.  
  4. #include "IAPIProviderInterface.h"
  5.  
  6. namespace seamless {
  7.  
  8. class Rank {
  9. public:
  10.         virtual ~Rank() {}
  11.  
  12. public:
  13.         void processQuery(IAPIProviderInterface* iAPIProvider);
  14. };
  15.  
  16. }  // namespace seamless
  17.  
  18. #endif // RANK_H_

Rank.cc 实现

  1. #include 
  2. #include 
  3. #include 
  4. #include 
  5. #include "IAPIProviderInterface.h"
  6. #include "IParameterInterface.h"
  7. #include "VariantField.h"
  8.  
  9. #include "Rank.h"
  10.  
  11. using namespace seamless;
  12. using namespace std;
  13.  
  14. namespace seamless {
  15.  
  16. void Rank::processQuery(IAPIProviderInterface* iAPIProvider) {
  17.         IParameterInterface* iParameter = iAPIProvider->getParameterInterface();
  18.         if (!iParameter) {
  19.                 cerr << "iParameter is NULL" << endl;
  20.                 return;
  21.         }
  22.  
  23.         int32_t isRetailWholesale = 0;
  24.         int32_t isUseAlipay = 0;
  25.  
  26.         VariantField* value = new VariantField;
  27.  
  28.         iParameter->getParameter("retail_wholesale", value);
  29.         isRetailWholesale = (strcmp(value->strVal, "0")) ? 1 : 0;
  30.  
  31.         iParameter->getParameter("is_use_alipay", value);
  32.         isUseAlipay = (strcmp(value->strVal, "0")) ? 1 : 0;
  33.  
  34.         cout << "isRetailWholesale:\t" << isRetailWholesale << endl;
  35.         cout << "isUseAlipay:\t" << isUseAlipay << endl;
  36.  
  37.         delete value;
  38.         delete iParameter;
  39. }
  40.  
  41. }  // namespace seamless
  • 从上面的例子中能够看出,引擎会传入一个IAPIProviderInterface对象,这个对象调用getParameterInterface()方法来获得Query中的Segment。
  • 所以,咱们须要Mock的对象也比较清楚了,就是要模拟引擎将Query的Segment传给这个模块。其实就是让=模拟iParameter->getParameter方法:我想让它返回什么样的值就返回什么样的值.

下面咱们开始Mock了:
MockIParameterInterface.h 模拟模拟IParameterInterface类

  1. #ifndef MOCKIPARAMETERINTERFACE_H_
  2. #define MOCKIPARAMETERINTERFACE_H_
  3.  
  4. #include <boost/cstdint.hpp>
  5. #include 
  6.  
  7. #include "IParameterInterface.h"
  8. #include "VariantField.h"
  9.  
  10. namespace seamless {
  11.  
  12. class MockIParameterInterface: public IParameterInterface {
  13. public:
  14.         MOCK_METHOD2(getParameter, int32_t(const char* name,  VariantField*& value));
  15. };
  16.  
  17. }  // namespace seamless
  18.  
  19. #endif // MOCKIPARAMETERINTERFACE_H_

MockIAPIProviderInterface.h 模拟IAPIProviderInterface类

  1. #ifndef MOCKIAPIPROVIDERINTERFACE_H_
  2. #define MOCKIAPIPROVIDERINTERFACE_H_
  3.  
  4. #include 
  5.  
  6. #include "IAPIProviderInterface.h"
  7. #include "IParameterInterface.h"
  8.  
  9. namespace seamless {
  10.  
  11. class MockIAPIProviderInterface: public IAPIProviderInterface{
  12. public:
  13.         MOCK_METHOD0(getParameterInterface, IParameterInterface*());
  14. };
  15.  
  16. }  // namespace seamless
  17.  
  18. #endif // MOCKIAPIPROVIDERINTERFACE_H_

tester.cc 一个测试程序,试试咱们的Mock成果

  1. #include <boost/cstdint.hpp>
  2. #include <boost/shared_ptr.hpp>
  3. #include 
  4. #include 
  5.  
  6. #include "MockIAPIProviderInterface.h"
  7. #include "MockIParameterInterface.h"
  8. #include "Rank.h"
  9.  
  10. using namespace seamless;
  11. using namespace std;
  12.  
  13. using ::testing::_;
  14. using ::testing::AtLeast;
  15. using ::testing::DoAll;
  16. using ::testing::Return;
  17. using ::testing::SetArgumentPointee;
  18.  
  19. int main(int argc, char** argv) {
  20.         ::testing::InitGoogleMock(&argc, argv);
  21.  
  22.         MockIAPIProviderInterface* iAPIProvider = new MockIAPIProviderInterface;
  23.         MockIParameterInterface* iParameter = new MockIParameterInterface;
  24.  
  25.         EXPECT_CALL(*iAPIProvider, getParameterInterface()).Times(AtLeast(1)).
  26.                 WillRepeatedly(Return(iParameter));
  27.  
  28.         boost::shared_ptr<VariantField> retailWholesaleValue(new VariantField);
  29.         retailWholesaleValue->strVal = "0";
  30.  
  31.         boost::shared_ptr<VariantField> defaultValue(new VariantField);
  32.         defaultValue->strVal = "9";
  33.  
  34.         EXPECT_CALL(*iParameter, getParameter(_, _)).Times(AtLeast(1)).
  35.                 WillOnce(DoAll(SetArgumentPointee<1>(*retailWholesaleValue), Return(1))).
  36.                 WillRepeatedly(DoAll(SetArgumentPointee<1>(*defaultValue), Return(1)));
  37.  
  38.         Rank rank;
  39.         rank.processQuery(iAPIProvider);
  40.  
  41.         delete iAPIProvider;
  42.  
  43.         return EXIT_SUCCESS;
  44. }
  • 第26行,定义一个执行顺序,所以在以前的Rank.cc中,是先调用iAPIProvider>getParameterInterface,而后再调用iParameter>getParameter,所以咱们在下面会先定义MockIAPIProviderInterface.getParameterInterface的指望行为,而后再是其余的。
  • 第27~28行,定义MockIAPIProviderInterface.getParameterInterface的的行为:程序至少被调用一次(Times(AtLeast(1))),每次调用都返回一个iParameter(即MockIParameterInterface*的对象)。
  • 第30~34行,我本身假设了一些Query的Segment的值。即我想达到的效果是Query相似http://127.0.0.1/search?retailwholesale=0&isuse_alipay=9。
  • 第36~38行,咱们定义MockIParameterInterface.getParameter的指望行为:这个方法至少被调用一次;第一次被调用时返回1并将第一个形参指向retailWholesaleValue;后续几回被调用时返回1,并指向defaultValue。
  • 第51行,运行Rank类下的processQuery方法。

看看咱们的运行成果:

isRetailWholesale: 0
isUseAlipay: 1

从这个结果验证出咱们传入的Query信息是对的,成功Mock!

现实中的例子

就如我以前所说的,上述的那个例子是我改过的,现实项目中哪有这么理想的结构(特别对于那些历来没有Develop for Debug思想的同窗)。
所以咱们来看看上述这个例子中实际的代码:其实只有IAPIProviderInterface.h不一样,它定义了一个模版函数,用于统一各类类型的接口: IAPIProviderInterface.h 真正的IAPIProviderInterface.h,有一个模版函数

  1. #ifndef IAPIPROVIDERINTERFACE_H_
  2. #define IAPIPROVIDERINTERFACE_H_
  3.  
  4. #include <boost/cstdint.hpp>
  5. #include 
  6.  
  7. #include "IBaseInterface.h"
  8. #include "IParameterInterface.h"
  9. #include "VariantField.h"
  10.  
  11. namespace seamless {
  12.  
  13. class IAPIProviderInterface: public IBaseInterface {
  14. public:
  15.         IAPIProviderInterface() {}
  16.         virtual ~IAPIProviderInterface() {}
  17.  
  18. public:
  19.         virtual int32_t queryInterface(IBaseInterface*& pInterface) = 0;
  20.  
  21.         template<typename InterfaceType>
  22.         InterfaceType* getInterface() {
  23.                 IBaseInterface* pInterface = NULL;
  24.                 if (queryInterface(pInterface)) {
  25.                         std::cerr << "Query Interface failed" << std::endl;
  26.                 }
  27.                 return static_cast<InterfaceType* >(pInterface);
  28.         }
  29. };
  30.  
  31. }
  32.  
  33. #endif // IAPIPROVIDERINTERFACE_H_

Rank.cc 既然IAPIProviderInterface.h改了,那Rank.cc中对它的调用其实也不是以前那样的。不过其实也就差一行代码:

  1. //      IParameterInterface* iParameter = iAPIProvider->getParameterInterface();
  2.         IParameterInterface* iParameter = iAPIProvider->getInterface<IParameterInterface>();

由于目前版本(1.5版本)的Google Mock还不支持模版函数,所以咱们没法Mock IAPIProviderInterface中的getInterface,那咱们如今怎么办?
若是你想作得比较完美的话我暂时也没想出办法,我如今可以想出的办法也只能这样:IAPIProviderInterface.h 修改其中的getInterface,让它根据模版类型,若是是IParameterInterface或者MockIParameterInterface则就返回一个MockIParameterInterface的对象

  1. #ifndef IAPIPROVIDERINTERFACE_H_
  2. #define IAPIPROVIDERINTERFACE_H_
  3.  
  4. #include <boost/cstdint.hpp>
  5. #include 
  6.  
  7. #include "IBaseInterface.h"
  8. #include "IParameterInterface.h"
  9. #include "VariantField.h"
  10.  
  11. // In order to Mock
  12. #include <boost/shared_ptr.hpp>
  13. #include 
  14. #include "MockIParameterInterface.h"
  15.  
  16. namespace seamless {
  17.  
  18. class IAPIProviderInterface: public IBaseInterface {
  19. public:
  20.         IAPIProviderInterface() {}
  21.         virtual ~IAPIProviderInterface() {}
  22.  
  23. public:
  24.         virtual int32_t queryInterface(IBaseInterface*& pInterface) = 0;
  25.  
  26.         template<typename InterfaceType>
  27.         InterfaceType* getInterface() {
  28.                 IBaseInterface* pInterface = NULL;
  29.                 if (queryInterface(pInterface) == 0) {
  30.                         std::cerr << "Query Interface failed" << std::endl;
  31.                 }
  32.  
  33.                 // In order to Mock
  34.                 if ((typeid(InterfaceType) == typeid(IParameterInterface)) ||
  35.                         (typeid(InterfaceType) == typeid(MockIParameterInterface))) {
  36.                         using namespace ::testing;
  37.                         MockIParameterInterface* iParameter = new MockIParameterInterface;
  38.                         boost::shared_ptr<VariantField> retailWholesaleValue(new VariantField);
  39.                         retailWholesaleValue->strVal = "0";
  40.  
  41.                         boost::shared_ptr<VariantField> defaultValue(new VariantField);
  42.                         defaultValue->strVal = "9";
  43.  
  44.                         EXPECT_CALL(*iParameter, getParameter(_, _)).Times(AtLeast(1)).
  45.                                 WillOnce(DoAll(SetArgumentPointee<1>(*retailWholesaleValue), Return(1))).
  46.                                 WillRepeatedly(DoAll(SetArgumentPointee<1>(*defaultValue), Return(1)));
  47.                         return static_cast<InterfaceType* >(iParameter);
  48.                 }
  49.                 // end of mock
  50.  
  51.                 return static_cast<InterfaceType* >(pInterface);
  52.         }
  53. };
  54.  
  55. }
  56.  
  57. #endif // IAPIPROVIDERINTERFACE_H_
  • 第33~49行,判断传入的模版函数的类型,而后定义相应的行为,最后返回一个MockIParameterInterface对象

tester.cc

  1. int main(int argc, char** argv) {
  2.         ::testing::InitGoogleMock(&argc, argv);
  3.  
  4.         MockIAPIProviderInterface* iAPIProvider = new MockIAPIProviderInterface;
  5.  
  6.         InSequence dummy;
  7.         EXPECT_CALL(*iAPIProvider, queryInterface(_)).Times(AtLeast(1)).
  8.                 WillRepeatedly(Return(1));
  9.  
  10.         Rank rank;
  11.         rank.processQuery(iAPIProvider);
  12.  
  13.         delete iAPIProvider;
  14.  
  15.         return EXIT_SUCCESS;
  16. }
  • 这里的调用就相对简单了,只要一个MockIAPIProviderInterface就能够了。
Google Mock Cookbook

这里根据Google Mock Cookbook和我本身试用的一些经验,整理一些试用方面的技巧。

Mock protected、private方法

Google Mock也能够模拟protectedprivate方法,比较神奇啊(其实从这点上也能够看出,Mock类不是简单地继承本来的接口,而后本身把它提供的方法实现;Mock类其实就等于本来的接口)。
protectedprivate方法的Mock和public基本相似,只不过在Mock类中须要将这些方法设置成public
Foo.h 带private方法的接口

  1. class Foo {
  2. private:
  3.         virtual void setValue(int value) {};
  4.  
  5. public:
  6.         int value;
  7. };

MockFoo.h

  1. class MockFoo: public Foo {
  2. public:
  3.         MOCK_METHOD1(setValue, void(int value));
  4. };
Mock 模版类(Template Class)

Google Mock能够Mock模版类,只要在宏MOCK*的后面加上T。
仍是相似上述那个例子:
Foo.h 改为模版类

  1. template <typename T>
  2. class Foo {
  3. public:
  4.         virtual void setValue(int value) {};
  5.  
  6. public:
  7.         int value;
  8. };

MockFoo.h

  1. template <typename T>
  2. class Foo {
  3. public:
  4.         virtual void setValue(int value) {};
  5.  
  6. public:
  7.         int value;
  8. };
Nice Mocks 和 Strict Mocks

当在调用Mock类的方法时,若是以前没有使用EXPECT_CALL来定义该方法的指望行为时,Google Mock在运行时会给你一些警告信息:

GMOCK WARNING:
Uninteresting mock function call – returning default value.
Function call: setValue(1)
Returns: 0
Stack trace

对于这种状况,可使用NiceMock来避免:

  1.         // MockFoo mockFoo;
  2.         NiceMock<MockFoo> mockFoo;
使用NiceMock来替代以前的MockFoo。

固然,另外还有一种办法,就是使用StrictMock来将这些调用都标为失败:

  1. StrictMock<MockFoo> mockFoo;

这时获得的结果:

unknown file: Failure
Uninteresting mock function call – returning default value.
Function call: setValue(1)
Returns: 0
 
标签:  google mock
相关文章
相关标签/搜索