Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

20
  • 52
    +1 bazillion. And if a private method is never called, don't unit-test it, delete it! Commented Aug 14, 2011 at 6:08
  • 387
    I disagree. Sometimes a private method is just an implementation detail, but it still is complex enough that it warrants testing, to make sure it works right. The public interface may be offering a too high level of abstraction to write a test which directly targets this particular algorithm. It's not always feasible to factor it out into a separate class, for due to the shared data. In this case I'd say it's OK to test a private method.
    – quant_dev
    Commented Aug 14, 2011 at 8:04
  • 50
    @quant_dev: Sometimes a class needs to be refactored into several other classes. Your shared data can be pulled into a separate class too. Say, a "context" class. Then your two new classes can refer to the context class for their shared data. This may seem unreasonable, but if your private methods are complex enough to need individual testing, it's a code smell that indicates your object graph needs to become a little more granular.
    – Phil
    Commented Jul 17, 2012 at 14:47
  • 114
    This answer DOES NOT answer the question. The question is how should private methods be tested, not whether they should be tested. Whether a private method should be unit tested is an interesting question and worthy of debate, but not here. The appropriate response is add a comment in the question stating that testing private methods may not be a good idea and give a link to a separate question which would go into the matter more deeply.
    – TallGuy
    Commented Jan 30, 2014 at 22:39
  • 21
    @TallGuy Allow me to distill my answer here to its core point. The answer to "how does one unit test private methods?" is "One doesn't."
    – Adam Lear
    Commented Jan 30, 2014 at 22:40