Praveen's Blog

An Eternal Quest for Incremental Improvement

How to unit test C++ private and protected member functions?

In the unit testing world, sometimes we encounter a situation where we need to unit test private or protected member functions. There is a lot of arguments surrounding this topic. Some claim that if a private member function needs testing, it implies that there is a need for refactoring. However, I strongly feel that protected member functions are still APIs and people often are in a situation where they need to unit test some of them. One of the simple ways that I found was to declare the test suite class to be the friend of that is to be tested. It is better to scope the declaration in an #ifdef block.

class Foo {
  public:
#ifdef UNITTEST
    friend class FooTest;
#endif
    ...

  protected:
    ...

  private:
    ...
};

It would be even better to come up with an helper macro like the following.

#ifdef UNITTEST
#define ASSIST_UNIT_TEST( class__ ) friend class class__##Test
#else
#define ASSIST_UNIT_TEST( class__ )
#endif

And use the above macro in the class to be tested.

class Foo {
  public:
    ASSIST_UNIT_TEST( Foo );
    ...

  protected:
    ...

  private:
    ...
};

We can have the macro UNITTEST to define only for the unit test code. During this exercise, I found that I dearly missed __CLASS__ macro in C++ badly! I documented this approach in the cppunit FAQ page.

I have also tried to create a wrapper class that derives from the class to be tested and override the protected functions so that they are in the public scope of the derived class. This can help testing only protected member functions. However there is a lot of new code involved in the wrapper class to invoke the base class' appropriate function. So, I consider this ineffective and error prone.

PS: If someone knows a better approach to do this in C++ please let me know.


Comments