从工厂模拟返回多个 unique_ptr
Returning multiple unique_ptr from factory mock
当无法通过对被调用函数的不同输入参数识别调用时,我如何 return 来自模拟工厂的多个对象 returning unique_ptr
?
我正在这样做:
EXPECT_CALL(MyFactoryMock, create())
.WillRepeatedly(Return(ByMove(std::make_unique<MyObjectTypeMock>())));
而运行-时间误差为:
[ FATAL ]
/.../tools/googletest/1.8.0-57/include/gmock/gmock-actions.h:604::
Condition !performed_ failed. A ByMove() action should only be
performed once.
只做一次同样的事情,使用 WillOnce
,效果很好。
后续问题:
ByMove
旨在移动您在测试中准备的预定义值,因此只能调用一次。如果你需要别的东西,你需要明确地自己写。
以下是 googletest documentation 的摘录:
Quiz time! What do you think will happen if a Return(ByMove(...))
action is performed more than once (e.g. you write ...
.WillRepeatedly(Return(ByMove(...)));
)? Come think of it, after the
first time the action runs, the source value will be consumed (since
it’s a move-only value), so the next time around, there’s no value to
move from – you’ll get a run-time error that Return(ByMove(...))
can
only be run once.
If you need your mock method to do more than just moving a pre-defined
value, remember that you can always use a lambda or a callable object,
which can do pretty much anything you want:
EXPECT_CALL(mock_buzzer_, MakeBuzz("x"))
.WillRepeatedly([](StringPiece text) {
return MakeUnique<Buzz>(AccessLevel::kInternal);
});
EXPECT_NE(nullptr, mock_buzzer_.MakeBuzz("x"));
EXPECT_NE(nullptr, mock_buzzer_.MakeBuzz("x"));
Every time this EXPECT_CALL
fires, a new unique_ptr<Buzz>
will be
created and returned. You cannot do this with Return(ByMove(...))
.
当无法通过对被调用函数的不同输入参数识别调用时,我如何 return 来自模拟工厂的多个对象 returning unique_ptr
?
我正在这样做:
EXPECT_CALL(MyFactoryMock, create())
.WillRepeatedly(Return(ByMove(std::make_unique<MyObjectTypeMock>())));
而运行-时间误差为:
[ FATAL ] /.../tools/googletest/1.8.0-57/include/gmock/gmock-actions.h:604:: Condition !performed_ failed. A ByMove() action should only be performed once.
只做一次同样的事情,使用 WillOnce
,效果很好。
后续问题:
ByMove
旨在移动您在测试中准备的预定义值,因此只能调用一次。如果你需要别的东西,你需要明确地自己写。
以下是 googletest documentation 的摘录:
Quiz time! What do you think will happen if a
Return(ByMove(...))
action is performed more than once (e.g. you write ....WillRepeatedly(Return(ByMove(...)));
)? Come think of it, after the first time the action runs, the source value will be consumed (since it’s a move-only value), so the next time around, there’s no value to move from – you’ll get a run-time error thatReturn(ByMove(...))
can only be run once.If you need your mock method to do more than just moving a pre-defined value, remember that you can always use a lambda or a callable object, which can do pretty much anything you want:
EXPECT_CALL(mock_buzzer_, MakeBuzz("x")) .WillRepeatedly([](StringPiece text) { return MakeUnique<Buzz>(AccessLevel::kInternal); }); EXPECT_NE(nullptr, mock_buzzer_.MakeBuzz("x")); EXPECT_NE(nullptr, mock_buzzer_.MakeBuzz("x"));
Every time this
EXPECT_CALL
fires, a newunique_ptr<Buzz>
will be created and returned. You cannot do this withReturn(ByMove(...))
.