Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 950
Jonhtra Avatar asked Jan 20 '12 13:01

Jonhtra


People also ask

Can static classes be mocked?

The powerful capabilities of the feature-rich JustMock framework allow you to mock static classes and calls to static members like methods and properties, set expectations and verify results. This feature is a part of the fastest, most flexible and complete mocking tool for crafting unit tests.

Can we mock static methods in junit5?

With some overhead you can: As JUnit 5 provides support for running legacy JUnit 4, and there you can use Mockito. So you can create tests in Junit4 for these cases: A sample project for migration setup with gradle and with mvn. From there I am using PowerMock 2.0 beta with Mockito 2.

How do you test static function in Gtest?

A static function has it's visibility limited to the translation unit. AFAIK, for googletest, you need to call the function(s) under test from a separate test file conating the test code written with TEST() .

What is Gmock and Gtest?

In real system, these counterparts belong to the system itself. In the unit tests they are replaced with mocks. Gtest is a framework for unit testing. Gmock is a framework imitating the rest of your system during unit tests.


1 Answers

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);};
like image 74
BЈовић Avatar answered Oct 04 '22 10:10

BЈовић