Search code examples
c++unit-testinggooglemock

Mocking - Methods & Tools


I have self learned gmock and understood its functionality. It would be great if we can mock some methods and test our flow.

My issue now is that we have huge code repo which calls upon many sub-module interfaces for a specific flow - i.e. underlying class method calls a number of sub-modules / sub-sub-modules interfaces:

  bool classA::methodA(uint64_t number) {
  if (0 == number) {
    return false;
  }
  Foo* p=&obj;
  while (true && (p->*fptr)(number)) {
    if (1 == number) {
      return true;
    } else if (0 == number%2) {
      number = number / 2;
    } else {
      Printer* machine;
      char* buff;
      PTR pmf[2]= {&B::Copy, &B::Append}; 
      (machine->*pmf[APPEND])(buff, number);
      number = 3 * number + 1;
    }
  }
}

Is there a method / mechanism / thumb rule by which we can identify / know all method of sub-modules which needs to be mocked to test my class 100% code?


Solution

  • There is no need for a rule here. You simply mock the things that require to be mocked. Nothing more, nothing less.

    Keep in mind: you write unit tests with the idea to test your unit in isolation. This means that you sometimes have to "cut out" dependencies that your unit has into other code.

    Now let's assume that your code is using some dependency B.

    • when you can invoke your code keeping the real B in place - fine. Then do that.
    • when B is either failing in your unit test setup or you need to control what B returns to your code - then you need a mock.

    In that sense, the rule of thumb is: mock things if you have to.

    Therefore we can't tell you what exactly you have to mock. Instead, you have to step back and:

    • first of all, understand how you want to unit test your code
    • then you look at its dependencies
    • then you maybe experiment what happens when you invoke your code without any mocks in place
    • then you draw your conclusions from the data gathered by the previous steps