google test mock入门

来源:互联网 发布:2016年广州家博会数据 编辑:程序博客网 时间:2024/05/02 00:31
1 导入google mock 名称,一般是testing
using ::testing::Return;                            // #1

2 创建mock 对象
  MockFoo foo;                                    // #2
 
3 第三步是可选的,设置为mock 对象的default action
  ON_CALL(foo, GetSize())                         // #3
      .WillByDefault(Return(1));
  // ... other default actions ...
 
4 设置你对mock对象的期望行为,比如如何被调用,将做什么
  EXPECT_CALL(foo, Describe(5))                   // #4
      .Times(3)
      .WillRepeatedly(Return("Category 5"));
  // ... other expectations ...
 
 5 对mock对象期望的行为进行验证,一般使用google test的断言
  EXPECT_EQ("good", MyProductionFunction(&foo));  // #5
 
 6 对象的析构,google mock 会自动处理
 
 
 完整的示例如下:
 using ::testing::Return;                            // #1

TEST(BarTest, DoesThis) {
  MockFoo foo;                                    // #2

  ON_CALL(foo, GetSize())                         // #3
      .WillByDefault(Return(1));
  // ... other default actions ...

  EXPECT_CALL(foo, Describe(5))                   // #4
      .Times(3)
      .WillRepeatedly(Return("Category 5"));
  // ... other expectations ...

  EXPECT_EQ("good", MyProductionFunction(&foo));  // #5

}                                                 // #6



Times()子句可以省略。如果你省略Times(),Google Mock会推断出你的基数。规则很容易记住:

  • 如果WillOnce()和WillRepeatedly()都不在EXPECT_CALL()中,则推断的基数是Times(1)。
  • 如果有n个WillOnce(),但没有WillRepeatedly(),其中n> = 1,基数是Times(n)
  • 如果有n个WillOnce()和一个WillRepeatedly(),其中n> = 0,基数是Times(AtLeast(n))。


  • Fake objects have working implementations, but usually take some shortcut (perhaps to make the operations less expensive), which makes them not suitable for production. An in-memory file system would be an example of a fake.
  • Mocks are objects pre-programmed with expectations, which form a specification of the calls they are expected to receive.


0 0