Google Mock unit testing static methods c++

Solution 1:

You could change class B into a template :

template< typename T >
class B
{
public:
static int Method2(int a, int b){ return T::Method1(a,b);}
};

and then create a mock :

struct MockA
{
  static MockCalc *mock;
  static int Method2(int a, int b){ return mock->Method1(a,b);}
};
class MockCalc {
 public:
  MOCK_METHOD2(Method1, int(int,int));
};

Before every test, initialize the static mock object MockA::mock.

Another option is to instead call directly A::Method1, create a functor object (maybe std::function type) in class B, and call that in the Method2. Then, it is simpler, because you would not need MockA, because you would create a callback to MockCalc::Method1 to this object. Something like this :

class B
{
public:
static std::function< int(int,int) > f;
static int Method2(int a, int b){ return f(a,b);}
};

class MockCalc {
 public:
  MOCK_METHOD2(Method1, int(int,int));
};

and to initialize it :

MockCalc mock;
B::f = [&mock](int a,int b){return mock.Method1(a,b);};