简体   繁体   English

从工厂模拟返回多个 unique_ptr

[英]Returning multiple unique_ptr from factory mock

How can I return multiple object from a mocked factory returning unique_ptr , when the calls cannot be identified through different input parameters to the called function?当无法通过对被调用 function 的不同输入参数识别调用时,如何从返回unique_ptr的模拟工厂返回多个 object?

I'm doing this:我正在这样做:

EXPECT_CALL(MyFactoryMock, create())
  .WillRepeatedly(Return(ByMove(std::make_unique<MyObjectTypeMock>())));

And run-time error is:运行时错误是:

[ FATAL ] /.../tools/googletest/1.8.0-57/include/gmock/gmock-actions.h:604:: Condition.performed_ failed. [致命] /.../tools/googletest/1.8.0-57/include/gmock/gmock-actions.h:604:: Condition.performed_ 失败。 A ByMove() action should only be performed once. ByMove() 动作只能执行一次。

Doing the same thing only once, using WillOnce , works fine.使用WillOnce只做一次同样的事情,效果很好。

ByMove is designed to move a predefined value that you prepared in your test, so it can only be called once. ByMove旨在移动您在测试中准备的预定义值,因此只能调用一次。 If you need something else, you'll need to write it yourself explicitly.如果您需要其他内容,则需要自己明确编写。

Here's an excerpt from the googletest documentation :这是googletest 文档的摘录:

Quiz time!小测验时间! What do you think will happen if a Return(ByMove(...)) action is performed more than once (eg you write... .WillRepeatedly(Return(ByMove(...))); )?如果多次执行Return(ByMove(...))动作(例如,您编写... .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.想一想,在第一次动作运行后,源值将被消耗(因为它是一个只移动的值),所以下一次,没有值可以移动——你会得到一个运行时Return(ByMove(...))只能运行一次的错误。

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:如果您需要模拟方法做的不仅仅是移动预定义的值,请记住,您始终可以使用 lambda 或可调用的 object,它们几乎可以做任何您想做的事情:

 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.每次触发此EXPECT_CALL时,都会创建并返回一个新的unique_ptr<Buzz> You cannot do this with Return(ByMove(...)) .你不能用Return(ByMove(...))做到这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM