Search code examples
c++unit-testinggooglemock

How to return one of the in-parameters in gmock


I thought this sounded simple enough but i cannot seem to figure out how to do it.. I'm mocking a linux socket interface using this mock function:

MOCK_CONST_METHOD4(send, int(int socketDescriptor, const void* buffer, size_t n, int flags));

I want to return the number of bytes written with send.

One idea was this:

  uint32_t nBytes = 0;

  EXPECT_CALL(socketMock, send(124, _, _, MSG_NOSIGNAL))
    .WillOnce(DoAll(SaveArg<2>(&nBytes),
                    Return(nBytes)));

But this will always return zero.

What should i do instead to Return(Arg<2>)?


Solution

  • Looking at the CheatSheat it looks like this is what you want:

    EXPECT_CALL(socketMock, send(124, _, _, MSG_NOSIGNAL))
        .WillOnce(::testing::ReturnArg<2>()));