Search code examples
c++googlemock

Workaround for gmock to support rvalue reference


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.


Solution

  • 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;
    }