Extreme Programming Testing Private Methods

Most classes have private methods. DeveloperTests cover behaviors, not methods. Some behaviors will ReFactor into private methods, as their public access points grew too long. So their tests are indirect.

Related Wiki Pages:

Yahoo Groups (was Egroups): For more XP implementation issues, see ExtremeProgrammingImplementationIssues

Q: How do we access the 'Egroups' references?
A: The archives are public and should be accessible via the above URLs. Anybody can subscribe.


Q: We are subscribed to egroups in the Digest mode, so we receive chunks of mails in one email, but in the Digest there are no references to real message numbers. Does anybody have a solution for this bug in Egroups? -- ArielErlijman
A: Try to look up archives by looking at the date of the message you are searching, or do a search of the archives with keywords in the message your are looking for.


To retrofit unit tests into legacy code sometimes you must crack open a "seam", and publicize your private methods. (Code designed without TestDrivenDevelopment can sometimes link into itself a little too incestuously.)

Sigh - introducing a seamd be so easy if C# supported ConditionalCompilation?, so you can do this without cluttering up the code view:

 #if (UNITTEST)
 public void myMethod()
 #else
 private void myMethod()
 #endif
 {
 ... method body ...
 }

You can leave it private and call it via reflection from your test. Gives you a bit more to code in the test, but leaves the implementation clean.


Actually a technique I've used in unit testing private members in C++ is:

 #define protected public
 #define private   public
 #include "TheClassHeaderUnderTest?.h"
 #undef protected
 #undef private

Rather dirty but it does give access. (And note, if you don't totally rebuild with the same definitions over "TheClassHeaderUnderTest?.h" for an entire executable before linking, you will violate C++'s One Definition Rule.)


See discussion on UnitTestingNonPublicMemberFunctions. -- OliverKamps


EditText of this page (last edited June 13, 2008) or FindPage with title or text search