Unit testing of private methods

Viewed 92023

I am in the process of writing some unit tests. In particular I want to test some private methods.

So far the I have come up with using.

#define private public

But I am not happy with this as it will destroy all encapsulation from the point of view of the unit test.

What methods do you use to unit-test private methods.

8 Answers

After many hours this is what I decided to be the best solution for ones that want to test their private functions. This is combination of answers by Max DeLiso and Miloš.

If you are using boost::unit-test then there's an easy and elegant solution.

  1. Use protected instead of private in your classes

    /* MyClass.hpp */
    
    class MyClass {
    
    protected:
        int test() {
            return 1;
        }
    };
    
  2. Create a fixture:

    /* TestMyClass.cpp */
    
    class F : public MyClass {};
    
    
    BOOST_FIXTURE_TEST_SUITE(SomeTests, F)
    
    // use any protected methods inside your tests
    BOOST_AUTO_TEST_CASE(init_test)
    {
        BOOST_CHECK_EQUAL( test(), 1 );
    }
    BOOST_AUTO_TEST_SUITE_END()
    

This way you can freely use any of the MyClass functions without #define private public or adding friends to you class!

Related