Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

GoogleMock – Returning a value based on mocked function variables

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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 };
})));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading