1

I have a simple mock class:

class MockCanInterface : public lib::CanInterface {
 public:
  MockCanInterface() : CanInterface({"mock"}) {}

  MOCK_METHOD1(Write, bool(const lib::CanFrame& frame));
  MOCK_METHOD1(Read, bool(lib::CanFrame* frame));
};

In the test code I want to pass an object to the Write method. Is there a way to do this with .With clause? It works with passing argument directly, but now with .With. The code compiles, but fails during execution - the size of the object is correct, but the data isn't.

This works:

EXPECT_CALL(can_, Write(expected_command_))
        .WillOnce(Return(true));

This doesn't:

EXPECT_CALL(can_, Write(_))
        .With(Args<0>(expected_command_))
        .WillOnce(Return(true));

I admit that there may be something missing in the way the code sets the expected object.

273K
  • 29,503
  • 10
  • 41
  • 64
ilya1725
  • 4,496
  • 7
  • 43
  • 68

1 Answers1

0

I think the point is: The method Write() required a CanFrame argument passed by reference.

I suggest to use the Actions provided by GMock:
SetArgReferee - reference or value
SetArgPointee - pointer

You can find examples and much more here

However this solution works for me, I hope for you too ;)

EXPECT_CALL(can_, Write(_))
        .WillOnce(SetArgReferee<0>(expected_command_));

or with the return value:

EXPECT_CALL(can_, Write(_))
        .WillOnce(DoAll(SetArgReferee<0>(expected_command_), Return(true)));
Soeren
  • 1,725
  • 1
  • 16
  • 30
  • thanks for the solution. Have you tried the code with mock `Write` taking `const lib::CanFrame&`? I keep getting this error `error: passing 'const lib::CanFrame' as 'this' argument discards qualifiers` – ilya1725 Jun 19 '17 at 21:14
  • you are right. It only works with a non-const reference. I can't find a solution to a const reference argument. However I leave my answer here, maybe it help someone to find the correct answer. – Soeren Jun 24 '17 at 09:42