Testing private methods: easier than you think!

Testing private methods is something that has traditionally drawn heated debates in the Java world.

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:

Don't test private methods

This really leaves us with three choices:
  • refactor to make the method public in some helper class
  • test through a calling method with a higher visibility
  • give up
A delightful choice between increased bloat, higher test complexity and resignation!

No, thank you!


Use reflection

Why make things simple when you can also make them hard and long-winded? Haven't you always been dreaming of needing 10 lines of code to make a method call? (Yes, there are now even entire tools dedicated to this big operation!) Extra bonus points because you can now also prevent your IDE's compiler and refactoring tools from helping you!

No, thank you!


Use a nested class

No too bad, but with 3 significant drawbacks:
  • no separate sources / test sources folders
  • larger classes
  • unit test code in production binaries
We can do better.

No thank you!


Change the visibility

This leaves us with the last option. Not perfect either, but by far the most pragmatic!

It trades a slight increase in visibility (to package-protected) for greatly simplified calling (a regular method call, no less!), while still preserving the valuable sources / test sources separation.

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. :-)

 


Axel

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

 

Architecting for Continuous Delivery and Zero Downtime

Two day intensive on-site training with Axel Fontaine

Upcoming dates

Iasi, Romania (May 10-11, 2017)
Oslo, Norway (Oct 16-17, 2017)

« One Minute Book Review: Getting To Yes
Optional Dependency Strategies for Java Libraries »
Browse complete blog archive
Subscribe to the feed