Kai-Uwe Bux said:
Dave Steffen wrote:
Am Sun, 08 Jul 2007 15:38:36 -0700 schrieb (e-mail address removed):
Hi,
I want to write a test function to test a class. The class has a
private member function that need to be tested. Although I could
modify the member function as protected or public, I do not want
to modify the class definition. I'm wondering what is the
standard way to test private member functions in a library.
[...]
I'm not sure it's guaranteed to work, but we've used the "#define
private public" hack in our unit tests. It's the only way I know
of to get access to a class' guts for testing purposes *without*
changing the source code.
Formally, that would be undefined behavior in any compilation unit
that includes at least one standard header. See [17.4.3.1.1/2]:
Yeah, I know.
It's a mildly tricky game to play. The first time
I saw it, I thought it was the most horrible thing I'd ever seen.
Interestingly, there was a thread a while back on
comp.lang.c++.moderated a while back about whether or not adding
"#define private public" could actually change the behavior of a
program (assuming the compiler did something reasonable, which isn't
guaranteed by the standard, but is true for popular compilers). The
answer was, IIRC, "Yes, but only if you're doing things you
shouldn't". Overloading member functions with different access
specifiers was the specific example somebody came up with.
So, yeah, not guaranteed to work, not guaranteed portable, but
(practically speaking) workable in some environments. I don't know
of any other way to test private methods *without touching the
source*.