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
Axel Fontaine is the founder and CEO of Boxfuse the easiest way to deploy JVM and Node.js applications to AWS.
Axel is also the creator and project lead of Flyway, the open-source tool that makes database migration easy.
He is a Continuous Delivery and Immutable Infrastructure expert, a Java Champion, a JavaOne Rockstar and a regular speaker at many large international conferences including JavaOne, Devoxx, Jfokus, JavaZone, QCon, JAX, ...
You can follow him on Twitter at @axelfontaine
Two day intensive on-site training with Axel Fontaine
Upcoming dates
Iasi, Romania (May 10-11, 2017)
Oslo, Norway (Oct 16-17, 2017)