Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GMock: Has to be always pure virtual the base class of a mock class?

Tags:

c++

googlemock

I have read about good practices in googlecode. And they are right, but I'm still curious about the following:

There is some class definition, lets say:

class A{
   virtual void method_a(){}
};

as you can see, method_a is not pure vitual.

Can I code

class MockA: public A{
    MOCK_METHOD(method_a, void());
};

with no dark results?

Even further. Can I override method_a in MockA ?

Like:

class MockA: public A{
    void method_a(){
        // Do something here.
    }
};
like image 252
Raydel Miranda Avatar asked Oct 20 '22 20:10

Raydel Miranda


1 Answers

Well, I just did a test, and it seems we can. I'm using that approach in order to test some class functions with more that 10 parameters.

According to Simplifying the Interface without Breaking Existing Code. From gmock cookbook.

For instance:

class SomeClass {
     ...
     virtual void bad_designed_func(int a, ...){ // This functions has up to 12 parameters.
                                                 // The others were omitted for simplicity.
};


class MockSomeClass: public SomeClass {
    ...
    void bad_designed_func(int a, ...){ // This functions recives 12 parameters.
                                        // The others were omitted for simplicity.
        ...   
        test_wat_i_want(a);  // Mock method call. I'm only interest in paramater a.
    }

    MOCK_METHOD1(test_wat_i_want, void(int a));
};

In my code, I don't have any abstract class (meaning no pure virtual functions at all). This, it's not a recommended approach but helps us to deal with legacy code.

like image 66
Raydel Miranda Avatar answered Oct 31 '22 13:10

Raydel Miranda