2012-07-10
Testing private methods: easier than you think!
The solutions usually fall into 4 categories:
- Don't test private methods
- Use reflection
- Use a nested class
- Change the visibility
Let's look at them in turn:
- refactor to make the method public in some helper class
- test through a calling method with a higher visibility
- give up
- no separate sources / test sources folders
- larger classes
- unit test code in production binaries
No thank you!
And with a simple documentation habit, it becomes clear to everyone why this design trade-off was made:
/* private -> testing */ void myMethodUnderTest() {
...
}
So the next time you face this problem, choose the pragmatic route. And enjoy a coffee while everyone else is still trying to complicate things. :-)
About Axel Fontaine
I'm an entrepreneur, public speaker and software development expert based in Munich.
I'm the creator of Sprinters. Sprinters lets you run your GitHub Actions jobs 10x cheaper on your own AWS account with secure, ephemeral, high-performance, low-cost runners within the privacy of your own VPC.
I also created CloudCaptain, previously known as Boxfuse. CloudCaptain is a cloud deployment platform enabling small and medium size companies to focus on development, while it takes care of infrastructure and operations.
Back in 2010, I bootstrapped Flyway, and grew it into the world's most popular database migration tool. Starting late 2017, I expanded the project beyond its open-source roots into a highly profitable business, acquiring many of the world's largest companies and public institutions as customers. After two years of exponential growth, I sold the company to Redgate in 2019.
In the past I also spoke regularly at many large international conferences including JavaOne, Devoxx, Jfokus, JavaZone, JAX and more about a wide range of topics including modular monoliths, immutable infrastructure and continuous delivery. As part of this I received the JavaOne RockStar speaker award. As a recognition for my contributions to overall Java industry, Oracle awarded me the Java Champion title.
You can find me on 𝕏 as @axelfontaine and email me at axel@axelfontaine.com