C++ returning a future
Asked Answered
P

2

6

I'm using google test and am trying to mock a method that returns a future. What I'm doing is creating some future object in a test case, then I do "when(mock.Call()).thenReturn(myFutureObject), but I get an error "use of deleted function std::future<_res>::future(const std::future<_Res>&)".

This is the code:

std::promise<MyClass> pr;
std::future<MyClass> fut { pr.get_future() };

std::cout << fut.valid() << std::endl; // this returns 1 so it seems I have a valid future object

EXPECT_CALL(mockSvc, mymethod()).WillOnce(Return(std::move(fut)));

// this "expected call" throws an error "use of deleted function std::future<_res>::future(const std::future<_Res>&)
// /usr/include/c++/7/future:782:7: note declared here
//    future(const future&) = delete;

I guess that I'm getting an error about future's copy constructor being deleted, so my question is, how do I "mock" a future object, that is, how to "return" a future without copying, and I did try to use "std::move" ? What am I missing here ?

Pillbox answered 30/1, 2021 at 17:32 Comment(1)
We still need a good answers to this.Swiftlet
P
2

Since gtest/gmock 1.10.0 - one can use lambdas instead of simple Return action. So try this:

std::promise<MyClass> pr;

EXPECT_CALL(mockSvc, mymethod()).WillOnce([&] 
 { return pr.get_future(); });

Porbeagle answered 30/1, 2021 at 18:18 Comment(0)
P
1

Finally, I was able to resolve it:

Before expecting a call, use the following:

ON_CALL(mockSvc, myMethod()).WillByDefault(Return(ByMove(pr.get_future)));

// after that verify the expected call, in order to avoid uninteresting mock call warning.

EXPECT_CALL(mockSvc, myMethod()).Times(1);

EDIT: You can also use EXPECT_CALL only with the "ByMove" in the Return. Otherwise gtest will by default look at the copy constructor which is, ofcourse, deleted.

Pillbox answered 30/1, 2021 at 19:58 Comment(1)
ByMove worked just fine!Cowgill

© 2022 - 2024 — McMap. All rights reserved.