use of variable in EXPECT_CALL

Viewed 198

I have a simple mock class for a serial interface:

class MockSerialPort : public drivers::SerialPort
{
  public:
    MockSerialPort() : SerialPort(){};

    MOCK_METHOD((Result<size_t>), Read, (uint8_t *, size_t, (const duration<int64_t, std::micro> &)), (override));
    MOCK_METHOD((Result<size_t>), Write, (const uint8_t *, size_t), (override));
};

During the expected Read call I'd like to know what the buffer length that the calling code is expecting so that I can copy the data to the buffer properly. For example:

EXPECT_CALL(port_, Read(NotNull(),length,_))
                .WillOnce(DoAll(SetArrayArgument<0>(&data[0], &data[length]), Return(length)));

What is the correct syntax to do it? If I specify the variable as above then the value in it is what we expect. But how do I not fail the expect call and actually store the value that the caller of Read specified?

1 Answers

In such "complicated" cases - use lamdba expression - or some other function, functor object:


EXPECT_CALL(port_, Read(NotNull(),_ ,_))
                .WillOnce([](uint8_t *data, size_t length, const duration<int64_t, std::micro> &) {
   // do with data and length whatever you want
   return length;
});

This is possible since gtest1.10 - but from the fact that you are using MOCK_METHOD - I see that you are using newest gtest.

In short - replace DoAll(....) with some functor object - like lambda expression.

Related