small medium large xlarge

05 Mar 2014, 16:37
John Pelochino (1 post)

BKGRND: I am testing a new circular buffer module. The buffer parameters are held in a struct. These struct members should be private since the client doesn’t need to touch them. BUT by hiding the members, testing becomes much more difficult. If the struct format is public in the header, I can directly look to make sure I’m pointing at the storage array, that my read index is correct, that my write index is correct, etc. If private, I can only test the interface, and while this is possible, it feels slower and more inefficient.

Q: Is there a proper way to test private variables and functions efficiently? Am I missing something fundamental? In the case of my buffer, should I put a copy of the struct format in my test file and cast the pointer to the hidden struct to access these hidden members?

02 Jul 2014, 11:24
Arnd R.Strube (88 posts)

Hi John,

Generally, it is preferred testing through the interface. However, there can be situations where you may have good reasons to want to access private parts of your production code.

In these cases, one possible way of doing that (with any C-based unit testing framework, really) is to

#include "source_to_be_tested.c"

from within your test case. Do not have the linker link it as well or you will get errors.

In this way, you can access all private members.


  1. Some C code does not compile well with the C++ compiler

  2. Since you are accessing implementation detail in your tests, they will break more easily in the event of code changes.

You must be logged in to comment