MOCK_METHOD#1(#2, #3(#4) )
  #2是你要mock的方法名称!#1表示你要mock的方法共有几个参数,#4是这个方法具体的参数,#3表示这个方法的返回值类型。很简单不是?!
// Account.h
// basic application data class
#pragma once
#include <string>
class Account
{
private:
std::string accountId;  //账号
long balance;           //存款 呃 还是叫余额吧
public:
Account();
Account(const std::string& accountId, long initialBalance);
//消费
void debit(long amount);
//收入
void credit(long amount);
//获取存款
long getBalance() const;
//获取账号
std::string getAccountId() const;
};
  上面这个类是为了方便模拟转账业务构造的一个账户类。类Account有debit(消费)、credit(收入)、getBalance(获取存款)和getAccountId(获取账号)四个方法。
// A facility class acts as an external DB
class AccountHelper
{
private:
std::map<std::string, Account> mAccount;
// an internal map to store all Accounts for test
public:
AccountHelper(std::map<std::string, Account>& mAccount);
void updateAccount(const Account& account);
Account findAccountForUser(const std::string& userId);
};
AccountHelper::AccountHelper(std::map<std::string, Account>& mAccount)
{
this->mAccount = mAccount;
}
void AccountHelper::updateAccount(const Account& account)
{
this->mAccount[account.getAccountId()] = account;
}
Account AccountHelper::findAccountForUser(const std::string& userId)
{
if (this->mAccount.find(userId) != this->mAccount.end())
return this->mAccount[userId];
else
return Account();
}
  上面这个类,扮演着数据库的角色。mock(模拟)出来的方法,都将用该类的函数替代实现。
  下面,我们来写一个测试用例来看看gmock的神奇作用。
  // Test case to test AccountService
  TEST(AccountServiceTest, transferTest)
  {
  std::map<std::string, Account> mAccount;
  mAccount["A"] = Account("A", 3000);
  mAccount["B"] = Account("B", 2000);
  AccountHelper helper(mAccount);
  MockAccountManager* pManager = new MockAccountManager();
  // specify the behavior of MockAccountManager
  // always invoke AccountHelper::findAccountForUser
  // when AccountManager::findAccountForUser is invoked
  EXPECT_CALL(*pManager, findAccountForUser(testing::_)).WillRepeatedly(
  testing::Invoke(&helper, &AccountHelper::findAccountForUser));
  // always invoke AccountHelper::updateAccount
  //when AccountManager::updateAccount is invoked
  EXPECT_CALL(*pManager, updateAccount(testing::_)).WillRepeatedly(
  testing::Invoke(&helper, &AccountHelper::updateAccount));
  AccountService as;
  // inject the MockAccountManager object into AccountService
  as.setAccountManager(pManager);
  // operate AccountService
  as.transfer("A", "B", 1005);
  // check the balance of Account("A") and Account("B") to
  //verify that AccountService has done the right job
  EXPECT_EQ(1995, helper.findAccountForUser("A").getBalance());
  EXPECT_EQ(3005, helper.findAccountForUser("B").getBalance());
  delete pManager;
  }
  首先,声明一个类MockAccountManager的实例pManager,在声明一个实现类AccountHelper实例helper。EXPECT_CALL的作用是将调用pManager方法替换成实现类helper的对应方法。此处,将pManager的findAccountForUser方法替换成helper的findAccount方法,将pManager的updateAccount方法替换成helper的updateAccount方法。
  后,再用gtest的断言机制EXPECT_EQ来判断结果。