Testing 101 - How to test private methods

Testing 101 - How to test private methods

Advent Calendar #12

A huge mistake a lot of developers make, especially newer ones is dealing with private methods when it comes to testing. This post shall give you clarity and solve this problem once and forever.

The mantra

Tests always call the public API.

The term public API might be as large as the HTTP API from your complete system, but it might just be the public functions of a class.

Private methods should be called in the public API methods. If they are not, then why would they even exist?

The problem with making private methods public

You might not get the point, get frustrated and think now:

Screw that, I will make it public anyways. It's faster and it works for me.

If so, please stay with me and think again.

Private methods are private because they do internal stuff. Internal stuff is very highly likely to change and nobody cares about the signature of a private method when refactoring.

That means, after the first change in the class, the chance that your test for it breaks, is gigantically high.

Further resources

Making methods static just for testing might be even worse. Read this.