Susie Susie -4 years ago 157
Java Question

Appropriate method encapsulation for unit testing

My class contains

14 private methods
and
1 public method
. The public method calls all the private method directly or indirectly via other private methods.

The public method also has a call to a
DAO
that queries the database.
I wrote a unit test for the class. Since you can't write unit test for private methods, I changed all the private methods to default access and wrote unit test for them.

I was told that I shouldn't change the encapsulation just for the purpose of testing. But my public method has a call to the DAO and gets its data from the call. Even if I were to write a test for the public method, I'm assuming it would be really long and complicated.

How should I approach this problem. On one hand, I have to write a really complicated test for the public method which accesses a DAO and on the other hand, change the access level of the methods and write short, simple test methods for them. What should I do?

Any suggestions will be greatly appreciated

Answer Source

Purists will tell you that the private methods could be extracted to another helper class providing accessible methods, and they could be right.

But if it makes sense to keep these utility methods inside the class, if the class is not part of a public API and is not intended to be subclassed (it could be final, for example), I don't see any problem with making some of its private methods package-protected or protected. Especially if this non-private visibility is documented, for example with the Guava annotation @VisibleForTesting.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download