1.7.2. Accessing protected elements

Usually you will protect internal members in your classes. Variables should almost always be private, in very rare cases protected. So they are out of reach for your testing code. Since variables are very internal you should not try to make them accessible somehow. The following sections show some patterns how to use member methods to intentionally grant access to parts which are actually internal.

1.7.2.1. Lifting class members

One of the simplest methods to get access to interesting methods is to use a using declaration in a simple derived class to lift the member into public area. Of course this is only possible for protected methods and not for private ones.

It may be a nice compromise to make a private method more general and more robust in order to make it protected and test it this way.

class Sample
{
   Sample();

  protected:

    void interesting_internal_method();
};


class TestSample : public Sample
{

 public:

   using Sample::interesting_internal_method;
};

// in test code
TestSample sample;
sample.interesting_internal_method();

1.7.2.2. Injecting a Mock Object

Another possibility is to implement access to internal variables via getter and setter methods. If you make such methods private and virtual you prevent its direct use but still have the chance to overload the getter method in the tests. This way it is possible to insert mock objects to replace internal variables.

class Sample
{
  private:

    virtual Complicated *getVariable()
    {
      return &variable;
    }

    Complicated    variable;
};


class MockComplicated : public Complicated
{
  // mock needed capabilities
};


class DerivedSample : public Sample
{
  private:

    virtual Complicated *getVariable()
    {
      return &mock;
    }

  public:

    MockingComplicated  mock;
};