Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

googletest - Google Mock unit testing static methods c++

I just started working on unit testing (using BOOST framework for testing, but for mocks I have to use Google Mock) and I have this situation :

class A
{
static int Method1(int a, int b){return a+b;}
};

class B
{
static int Method2(int a, int b){ return A::Method1(a,b);}
};

So, I need to create mock class A, and to make my class B not to use real Method1 from A class, but to use mock.

I'm not sure how to do this, and I could not find some similar example.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...