Testing Private Methods

One of my Mentor Program participants just asked me about testing private methods. Here's my response:

Generally, you should be able to test private methods by calling a public method in such a way that it calls the private method. Remember, when you're writing a private method, you're engaging in encapsulation and information hiding. You're saying "this method is an implementation detail, not an important part of the class's interface." And tests are supposed to document the public behavior, not the internal implementation. So testing a private method can be a sign of a problem.

Sometimes you really need to test a private method. The quick-and-easy solution is to make the method public, and I'll admit that I've done so on occasion. (Often, I'll mark it "for testing only!") But that makes your class's interface more confusing and reduces its self-documentation. It's harder to understand a class's responsibilities if there's no way to tell public behavior from implementation detail.

If you need to make private methods public, it may be a sign that your class has become too big and complex. Often these sorts of classes need to be split into multiple, smaller classes with more clearly defined responsibilities. Once you do that, private methods often become public, because now they're part of the interface that defines the class's behavior, not just an implementation detail.

If you liked this entry, check out my best writing and presentations, and consider subscribing to updates by email or RSS.