Jonhtra
Jonhtra

Reputation: 957

Google Mock unit testing

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
{
  A(){}
  virtual int Method1(int a, int b){return a+b;}
};

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

Is it possible to do testing of class B, in that way to use mocked Method1 instead of real method, but not to change class B? I know this would be easy :

class B
{
  B(A *a):a_in_b(a){}
  static int Method2(int a, int b){return a_in_b->Mehod1();}
  A *a_in_b;
};

Upvotes: 0

Views: 5486

Answers (2)

ztao.87
ztao.87

Reputation: 31

you could firstly change your Class A into a Singleton, just like :

class A
{
    A* Instance();
    virtual int Method1(int a, int b){return a+b;}
    static A* A_instance;
    A(){}
};
A::A_instance = NULL;

and then mock Class A:

#include <gmock/gmock.h>
class MockA : public A
{
    public:
        MOCK_METHOD2(Method1, int(int a, int b));
};

and change A(). into A::Instance()-> after; then, you can use following methods to let Class B calling mock method on runtime:

MockA mock;
A::A_instance = &mock;
EXPECT_CALL(mock, Method(_, _))
......(you can decide the times and return values of the mock method) 

for more information, you can read the gmock cookbook at http://code.google.com/p/googlemock/wiki/CookBook

Upvotes: 1

jzwiener
jzwiener

Reputation: 8452

You could follow the guide on http://code.google.com/p/googlemock/wiki/ForDummies to build you a mock of A:

#include <gmock/gmock.h>
class MockA : public A
{
public:
    MOCK_METHOD2(Method1, int(int a, int b));
};

Before calling Method2 in class B make sure B knows the mock of A (assign the variable in B with the Mockobject of A) and execute an EXPECT_CALL:

MockA mock;
EXPECT_CALL(mock, Method1(_, _)
    .WillRepeatedly(Return(a + b);

Make sure that the variables a and b are valid in the execution context of the test.

Upvotes: 0

Related Questions