C++ 使用Gmock调用成员函数
这是我第一次使用gmock,并且有这个模拟类的例子C++ 使用Gmock调用成员函数,c++,googlemock,C++,Googlemock,这是我第一次使用gmock,并且有这个模拟类的例子 class MockInterface : public ExpInterface { public: MockInterface() : ExpInterface() { ON_CALL(*this, func(testing::_)).WillByDefault(testing::Invoke([this]() { // I need to fill the testVec with
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;
};
class MockInterface:公共接口
{
公众:
MockInterface():ExpInterface()
{
ON_CALL(*this,func(testing::)).WillByDefault(testing::Invoke([this](){
//我需要用作为参数传递给func的向量填充testVec
返回true;});
}
模拟方法1(func,bool(const std::vector&);
~MockInterface()=默认值;
私人:
std::vector_testVec;
};
然后我创建了MockInterface的一个实例
auto mockInt = std::make_shared<MockInterface>();
auto mockInt=std::make_shared();
调用
mockInt->func(vec)时
我需要用传入func
函数参数的向量填充_testVec,如何使用gMock执行此类操作?您可以使用SaveArg
操作:
ON_CALL(*this, func(::testing::_)).WillByDefault(
::testing::DoAll(
::testing::SaveArg<0>(&_testVec),
::testing::Return(false)));
请记住,Invoke
将把mock接收到的所有参数传递给被调用的函数,并且它必须返回与mock函数相同的类型。如果希望它不带参数,请使用InvokeWithoutArgs
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();});