Unit tests: How to access private members in C++

2015/07/17

Tags: c++ unit test private class members

In order to write unit tests sometimes one needs to access private class members or methods.
There are a couple of ways to do this in C++:

1. Use the friend keyword for the test classes or methods:

class ToTest  
{  
public:  
    void foo();  
    int bar();  
private:  
    void private_foobar();  
    int m_private_value;  
  
    friend void testToTest();  
};  
  
void testToTest(){  
    ToTest testObj;  
//  test testObj.m_private_value  
}

This method is usable but it means modifying production code in order to add tests.

2. Use preprocessor defines to change the access level

class ToTest  
{  
public:  
    void foo();  
    int bar();  
#ifdef UNIT_TESTS  
public:  
#else  
private:  
#endif  
    void private_foobar();  
    int m_private_value;  
};  

This method is still intrusive and adds modifications to production code. Also, you need separate builds for testing and deployment.

3. Define private as public for the tested class

#define private public  
#include <class_to_test.h>  
#define private private  

This method is non-intrusive, easiest and it allows to test everything in one single build. It will yield some compiler warnings, but they can be ignored, for the sake of testing.