gpt4 book ai didi

unit-testing - GMock : Capture a reference argument in a mocked function

转载 作者:行者123 更新时间:2023-12-05 03:08:04 27 4
gpt4 key购买 nike

我有一个具有引用参数的模拟函数:

MOCK_METHOD(func, void(MyObj &obj);

我想将 obj 捕获到一个变量中,以便我可以在单元测试中调用它的方法。所以像这样:

MyObj *capturedObj;
EXPECT_CALL(foo, func(testing::_)).WillOnce(<capture arg into capturedObj>);
capturedObj->bar();

我如何实现这一点?

最佳答案

一种可能的方法是调用一个单独的测试函数来为您捕获参数。

这可以通过 Invoke() 操作来完成,如 documentation 中所述:

Invoke(f) Invoke f with the arguments passed to the mock function, where f can be a global/static function or a functor.

Invoke(object_pointer, &class::method) Invoke the method on the object with the arguments passed to the mock function.

在您的情况下,类似下面的代码应该可以工作:

// Globally, outside your test case
MyObj *capturedObj;

void captureObj(MyObj &obj) {
captured = &obj;
}

// [..]

// In your test case
EXPECT_CALL(foo, func(testing::_)).WillOnce(testing::Invoke(captureObj));
capturedObj->bar();

如果使用测试夹具,capturedObjcaptureObj 可以是类成员,需要更新语法如下:

  EXPECT_CALL(foo, func(testing::_)).WillOnce(testing::Invoke(this, &TestFixtureClass::captureObj));

关于unit-testing - GMock : Capture a reference argument in a mocked function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46157888/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com