如何调用传递给 Mock 方法的函数指针?
How to call function pointer which is passed to Mock method?
virtual void doSomething(std::function<void(std::error_code result)> callback) = 0
MockMethod1(doSomething, std::function<void(std::error_code result)> callback);
现在写EXPECT_CALL的时候怎么调用"callback"
EXPECT_CALL(object, doSomething(testing::_)).WillRepeatedly( ??? );
我应该写什么来调用我的回调?
使用自定义操作来实现这一点。为了获得更大的灵活性,我建议为一个动作创建一个模板,其中模板参数表示 doSomething
中回调函数的参数索引。以下是您的操作方法:
ACTION_TEMPLATE(ExecuteCallback, HAS_1_TEMPLATE_PARAMS(unsigned, uIndex), AND_1_VALUE_PARAMS(callbackArg))
{
(std::get<uIndex>(args))(callbackArg);
}
请注意,如果需要,您可以添加更多值参数。现在,在您的测试中,您可以像这样调用设置模拟调用:
EXPECT_CALL(object, doSomething(testing::_)).WillRepeatedly(DoAll(ExecuteCallback<0>(err), Return()));
无需执行自定义操作。
我找到了不同的答案,
这是你需要做的,
EXPECT_CALL(.....).WillRepeatedly(testing::InvokeArgument<1>(arg1, arg2, ..));
virtual void doSomething(std::function<void(std::error_code result)> callback) = 0
MockMethod1(doSomething, std::function<void(std::error_code result)> callback);
现在写EXPECT_CALL的时候怎么调用"callback"
EXPECT_CALL(object, doSomething(testing::_)).WillRepeatedly( ??? );
我应该写什么来调用我的回调?
使用自定义操作来实现这一点。为了获得更大的灵活性,我建议为一个动作创建一个模板,其中模板参数表示 doSomething
中回调函数的参数索引。以下是您的操作方法:
ACTION_TEMPLATE(ExecuteCallback, HAS_1_TEMPLATE_PARAMS(unsigned, uIndex), AND_1_VALUE_PARAMS(callbackArg))
{
(std::get<uIndex>(args))(callbackArg);
}
请注意,如果需要,您可以添加更多值参数。现在,在您的测试中,您可以像这样调用设置模拟调用:
EXPECT_CALL(object, doSomething(testing::_)).WillRepeatedly(DoAll(ExecuteCallback<0>(err), Return()));
无需执行自定义操作。
我找到了不同的答案, 这是你需要做的,
EXPECT_CALL(.....).WillRepeatedly(testing::InvokeArgument<1>(arg1, arg2, ..));