a basic mantra: don’t test things where they’re hard to test.
a very basic application of this mantra comes up for almost every noob TDD’er: “how do i test this complex private method?”
the answer is simple: make it not private somewhere else and test it there instead.
if your private is truly complex, it’s truly interesting, and needs testing. but ask why it has to be private? the most common answer: “i don’t want to expose it to users of MyCoolObject because applied wrong it could end life as we know it.” now, that’s an entirely legitimate answer. nobody wants to be the one who exposed the API that ruined everything for everyone forever.
but remember that every class is a scope. you know this already or you wouldn’t be using ‘private’ at all. private controls what’s visible. so. make a new class. give it a public method that is the complex private you had before. make it in MyCoolObject’s constructor. call it. sure, it’s public over on OldPrivateMethod’s scope. but not on MyCoolObject’s, what u wanted by having it be private in the first place.
a complication arises, AND IT’S A GOOD ONE SO SUFFER THE PAIN THE FIRST FEW TIMES UNTIL YOU GET IT.
what if your complex private uses a whole bunch of fields from MyCoolObject? we enter judgment territory here. q: does it use all the fields from MyCoolObject? some, a couple, none?
if it’s a couple: pass them in. no biggie.
if it’s some, you’re very likely looking at one or more smells. here are some of the possible smells you might find in this case.
do u have temporary fields? does MyCoolObject have too many responsibilities? do the used (some) fields need aggregation to a new object?
if it’s all, then in fact you have a simple situation, tho it seems scary when u first see it: those fields belong on OldPrivateMethod…
after all, MyCoolObject can use them just as easily with them living on OldPrivateMethod as it does on itself.
the reason i mention the pain? well, it goes back to the driving premise. remember, tests & testability are first-class citizens in design. when you’re a noob, this feels hard. it gets much easier, but you have to play through for a while to get the pieces put together correctly.
anyway, hang in there, and think about that mantra: “if it’s hard to test here, why not test it somewhere else?”