Search code examples
googlemock

Capture GMOCK string parameter


If I have the following interface member function:

virtual bool print_string(const char* data) = 0;

with the following mock

MOCK_METHOD1(print_string, bool(const char * data));

Is it possible to capture the string that is passed to print_string()?

I tried to:

char out_string[20];     //
SaveArg<0>(out_string);  // this saves the first char of the sting

this saves the first char of the sting but not the whole string.


Solution

  • Class

    struct Foo {
        virtual bool print_string(const char* data) = 0;
    };
    

    Mock

    struct FooMock {
        MOCK_METHOD1(print_string, bool(const char * data));
    };
    

    Test

    struct StrArg {
        bool print_string(const char* data) { 
            arg = data; 
            return true; 
        }
        string arg;
    };
    
    TEST(FooTest, first) {
        FooMock f;
        StrArg out_string;
    
        EXPECT_CALL(f, print_string(_))
            .WillOnce(Invoke(&out_string, &StrArg::print_string));
        f.print_string("foo");
        EXPECT_EQ(string("foo"), out_string.arg);
    }
    

    You can always use Invoke to capture parameter value in structure.