Home > C++ > Publicizing My Private Parts

Publicizing My Private Parts

Check out the simple unit test code fragment below. What the hell is the #define private public preprocessor directive doing in there?

redefine

Now look at the simple definition of MyClass:

MyClass

The purpose of the preprocessor #define statement is to provide a simple, elegant way of being able to unit test the privately defined MyClass::privateImpl() function. It sure beats the kludgy “friend class technique” that blasphemously couples the product code base to the unit test code base, no? It also beats the commonly abused technique of specifying all member functions as public for the sole purpose of being able to invoke them in unit test code, no?

Since the (much vilified) C++ preprocessor is a simple text substitution tool, the compiler sees this definition of MyClass just prior to generating the test executable:

publicpublic

Embarassingly, I learned this nifty trick only recently from a colleague. Even more embarassingly, I didn’t think of it myself.

In an ideal world, there is never a need to directly call private functions or inspect private state in a unit test, but I don’t live in an ideal world. I’m not advocating the religious use of the #define technique to do white box unit testing, it’s just a simple tool to use if you happen to need it. Of course, it would be insane to use it in any production code.

Arne Mertz has a terrific post that covers just about every angle on unit testing C++ code: Unit Tests Are Not Friends.

Categories: C++ Tags:
  1. April 24, 2016 at 10:50 am

    Python has taught me that private is just a namespace and s the developer you most likely are only denying yourself the privilege of using the segregated namespace you have created for religious reasons. It used to be the operators(administrators) vs. the users(developers). It still is.

  2. April 24, 2016 at 5:00 pm

    Looks neat, but isn’t it a bit odd to write tests against “private api”?

    • April 24, 2016 at 8:47 pm

      Yes, but there may be times when it is needed. It’s not a perfect world 🙂

  3. Kapten mugg
    April 26, 2016 at 12:56 am

    If you need to write unit tests for your private parts, you most probably have a “god class”.

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: