c++ - 使用 Gmock 调用成员函数
问题描述
这是我第一次使用 gmock 并且有这个 Mock 类的例子
class MockInterface : public ExpInterface
{
public:
MockInterface() : ExpInterface()
{
ON_CALL(*this, func(testing::_)).WillByDefault(testing::Invoke([this]() {
// I need to fill the testVec with the vector passed as parameter to func
return true; }));
}
MOCK_METHOD1(func, bool(const std::vector<int>&));
~MockInterface() = default;
private:
std::vector<int> _testVec;
};
然后我创建了一个 MockInterface 实例
auto mockInt = std::make_shared<MockInterface>();
调用时,mockInt->func(vec);
我需要用传入func
函数的向量来填充 _testVec,如何用 gMock 做这种事情?
解决方案
您可以改用SaveArg
操作:
ON_CALL(*this, func(::testing::_)).WillByDefault(
::testing::DoAll(
::testing::SaveArg<0>(&_testVec),
::testing::Return(false)));
如果要调用成员函数,可以使用 lambda 或指向成员的指针语法。
ON_CALL(*this, func(::testing::_)).WillByDefault(
::testing::Invoke(this, &MockInterface::foo);
ON_CALL(*this, func(::testing::_)).WillByDefault(
::testing::Invoke([this](const std::vector& arg){ return foo();});
请记住,这Invoke
会将模拟接收到的所有参数传递给被调用的函数,并且它必须返回与模拟函数相同的类型。如果你想要它没有 args,请使用InvokeWithoutArgs
.
推荐阅读
- list - 在 Ansible 中创建列表时添加“未定义”条目
- mongodb - MongoDB聚合管道,字符串拆分后更新数组中的现有元素
- python - 带有动态构建列的 Pandas 数据框和带有 NaN 的整数数据?
- javascript - 如何在 pug 文件中调用外部 JavaScript 函数?
- registry - 需要注册表中的变量列表
- google-bigquery - Bigquery - 给定一个地理点和距离如何在它周围获得一个多边形
- performance - 更新目标 pod 时如何减少 nginx 入口路由的停机时间?
- r - Shiny Server 缺少由 R markdown 文件生成的图表
- javascript - 如何以角度获取区域下的所有svg对象?
- c++ - Is new T() equivalent to `mem = operator new(sizeof(T)); new(mem)T`?