google test mock入门

本文介绍如何使用GoogleMock库创建mock对象并设置其预期行为,包括导入名称、创建mock对象、设置默认行为及期望行为,并通过示例展示完整的单元测试过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

惹不起的程咬金

来都来了,不赏点银子么

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值