mock method with 11 parameters with gmock

2019-06-20 00:24发布

问题:

I'm using gmock to mock my dependencies in legacy code. One of the class have a method with 11 parameters. When I tried to use MOCK_METHOD11_WITH_CALLTYPE to mock it, I found this macro doesn't exist. gmock only supoort up to 10 parameters. What do you suggest for this? Do I implement this method with dummy body? Or copy & extend the macro? Thanks!

PS, I don't need to mock this method in my tests right now, but probably need to do so in the future.

Best regards,

回答1:

Methods with more than 10 parameters may be a sign of trouble. I can suggest a workaround which will help your specific case but which may also be a good idea apart from mocking. Take several of the parameters that make sense as a group, and aggregate them in a struct. Then pass an instance of that struct as an argument to the method. So instead of 11 arguments you might then have 3 or 4. Not only does this help with the mock library problem you're having, it may improve the usability of your class, since methods with so many arguments are usually difficult to read at the call site.



回答2:

In case someone needs more gmock arguments here is a header-only extension: gmock-more-args



回答3:

Method you are trying to mock is pure virtual. Here is what I did without changing my existing code:

struct ParamsMoreThanTen
{
  Param_Type param_1;
  Param_Type param_N;
};

MOCK_METHOD1(methodWithMoreThanTenParms, methodReturnType(ParamsMoreThanTen params));

methodReturnType methodWithMoreThanTenParms(
    Param_Type param_1,
    Param_Type param_N) override
{

  return    methodWithMoreThanTenParms(ParamsMoreThanTen
  {
    Param_Type param_1,
    Param_Type param_N
  });

};