Skip to main content

Command Palette

Search for a command to run...

Testing 101 - How to test private methods

Advent Calendar #12

Published
1 min read
Testing 101 - How to test private methods
A

Software developer and CEO at RoyalZSoftware. I build web applications for startups with Ruby on Rails, Angular and React.

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.

21 views

More from this blog

R

RoyalZSoftware

76 posts

This blog is about software development best practices and insights from RoyalZSoftware. Read it to advance your coding journey or to understand what we are doing for your software project.