Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Workaround for gmock to support rvalue reference

Tags:

c++

gmock

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.

like image 768
Edmund Avatar asked Aug 23 '12 09:08

Edmund


1 Answers

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;
}
like image 76
Edmund Avatar answered Sep 20 '22 02:09

Edmund