C++ returning a future

lin*_*oob 5 c++ unit-testing future mocking promise

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;
Run Code Online (Sandbox Code Playgroud)

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 ?

Pio*_*ycz 1

从 gtest/gmock 1.10.0 开始 - 可以使用 lambda 代替简单的 Return 操作。所以试试这个:

std::promise<MyClass> pr;

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

Run Code Online (Sandbox Code Playgroud)