10

gmock does not support rvalue reference as parameter of mocked function (issue report).

For example the following code will not compile:

MOCK_METHOD1(foo,void(std::string&&));

I can't find information on when gmock will add support to this.

273K
  • 29,503
  • 10
  • 41
  • 64
Edmund
  • 697
  • 6
  • 17

1 Answers1

13

I figured out a workaround: use a non-mocked function foo(std::string&& s){foo_rvr(s)} to relay the function to a mocked function foo_rvr(std::string). Here is the complete program.

#include <string>
#include <gtest/gtest.h>
#include <gmock/gmock.h>

class RvalueRef
{
public:
    virtual void foo(const std::string&)=0;
    virtual void foo(std::string&&)=0;
};

class MockRvalueRef : public RvalueRef
{
public:
    void foo(std::string&& s){foo_rvr(s);}
    MOCK_METHOD1(foo,void(const std::string&));
    MOCK_METHOD1(foo_rvr,void(std::string));
};

TEST(RvalueRef, foo)
{
    MockRvalueRef r;
    {
        ::testing::InSequence sequence;
        EXPECT_CALL(r,foo("hello"));
        EXPECT_CALL(r,foo_rvr("hi"));
    }

    std::string hello("hello");
    r.foo(hello);
    r.foo("hi");    
}

int main(int argc, char* argv[])
{
    ::testing::InitGoogleMock(&argc,argv);

    int rc=RUN_ALL_TESTS();

    getchar();
    return rc;
}
Edmund
  • 697
  • 6
  • 17
  • Another variant of this workaround can be found here: http://stackoverflow.com/questions/7616475/can-google-mock-a-method-with-a-smart-pointer-return-type/11548191#11548191 – πάντα ῥεῖ Aug 23 '12 at 10:01
  • 1
    Thank you, g-makulik, after viewing that post, I think we are using the same technique - using proxy to bypass the limitation of gmock. – Edmund Aug 23 '12 at 12:22
  • Yes, it's exactly the same technique of proxying the call. Nevertheless keep in mind my comments on memory management constraints when using this workaround with smart pointers. – πάντα ῥεῖ Aug 23 '12 at 17:17