Home > Blockchain >  GoogleMock - Returning a value based on mocked function variables
GoogleMock - Returning a value based on mocked function variables

Time:06-03

I'm trying to mock a function that accepts a struct and returns another one. Something like

struct InParams {
  int important_value;
  int other_value;
}

struct OutParams {
  int same_important_value;
  int idk_something;
}

virtual OutParams MyClass::TransformParams(const InParams& params){
...
}

When making a mocking function I want the OutParam struct to be dependant of InParam. So I made a mocking class and function

class MockMyClass : public MyClass {
public:
  MOCK_METHOD(OutParams, TransformParams,
              (const InParams& params), (const, override));
};

OutParams FakeOutParams(const InParams& in_parm){
  return {in_parm.important_value, 1};
}

And in expectant call I try to use it like this

auto fake_wrapper = new MockMyClass();
EXPECT_CALL(*fake_wrapper, TransformParams(_))
      .WillRepeatedly(
          WithArg<0>(Return(FakeOutParams)));

Which fails to compile. I also tried using SaveArgPointee but since InParams wasnt a pointer it also wasn't enough

What can I do to fix my issue?

CodePudding user response:

When you use Return it takes the object of returned type as argument, by copy. If you want to be more generic, and alter your return value with respect to some logic, use a gmock action. E.g. Invoke will be fine here:

EXPECT_CALL(*fake_wrapper, TransformParams(_))
      .WillRepeatedly(Invoke([](const InParams& params) { return FakeOutParams(params); })));

or directly move logic to lambda:

EXPECT_CALL(*fake_wrapper, TransformParams(_))
      .WillRepeatedly(Invoke([](const InParams& params) {
      return OutParams{ params.important_value, 1 };
})));
  • Related