Sorin Tirc
Sorin Tirc

Reputation: 123

Static pointer to this defined inside class for mock for googletest

I'm trying to understand why a piece of code from production was designed in the following way: To give people some context, there is a class A containing a method, call it some_method, that needs to be mocked. The mock and all the tests need to be isolated from the production code. So what my colleagues did was redefine this class inside the test folder in the following way:

class A
{
    class mockA
    {
     public: 
          mockA()
          {
              pointer_mockA = this;
          }
          virtual ~mockA(){
               pointer_mockA = NULL;
          }
         MOCK_METHOD1(some_method, string&(bool x));
         static mockA* pointer_mockA;

     }
string &some_method(bool x);

}

Also in the header file, some_method() is defined in the following way:

string& some_method(bool x)
    {
        return mockA::pointer_mockA->some_method(x);
    }

mockA::pointer_A is initialized to NULL in the cpp testing-file.

Questions

  1. Does pointer_mockA, as a static pointer, point to the current instance of the class A? Or simply just why is it used?
  2. Why is class A redefined in this testing header file, when it already exists in the folder where the code that needs to be tested exists?
  3. Is this design common? Is there no other simpler design?
  4. Any other comments on the code are very appreciated.

Upvotes: 1

Views: 365

Answers (1)

Bernd
Bernd

Reputation: 2221

1. pointer_mockA is pointing to the last created instance or to nothing / nullptr. It points to nothing after app start and after every destruction af a mockA object.

2. The reason could be, because mockA is a nested class of A. Unfortenately c++ does not allow isolated definitions of those nested classes. It is only possible to forward declare a nested class in the outer class and define it later.

3. Is it common? I would say no. There are some strange things: why is pointer_mockA a public field. Why is there this static pointer? What is the definition of the Macro MOCK_METHOD1? Is it important to be a polymorphic class (virtual destructor)?

Upvotes: 1

Related Questions