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

StackOverflow https://stackoverflow.com/questions/20226619

  •  05-08-2022
  •  | 
  •  

سؤال

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.
    }
};
هل كانت مفيدة؟

المحلول

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top