How dare you test a private method

I feel inspired to talk more about “testing a private method” (gasp!). Since people seem to get upset about it.

Where did this idea of it being bad even come from? I remember when learning to code it was all over the place. Blog posts, books, podcasts.

I remember being asked it as a trick question in interviews: "which code should you test?". Then the interviewer would nod as soon as I'd say "the public methods, never private!", to signal we have read the same blog posts.

Like any rule or best practice. You need to understand the context. Giving the advice of “do not test private methods” is a useful guideline for people new to testing. It protects them from common testing mistakes. Such as duplicate coverage/unnecessary tests. It also encourages people to have tests for their most important code paths (the public ones, that their users hit!). It's good advice!

Can I break the rule?

Sure! If you know what you’re doing and aren’t making those common mistakes. And have a scenario where testing a private method makes your codebase better in some way. Go for it. It’s just a “best practice”. We don’t always have to color inside the lines and can use our judgement on when to break the rules.