There are three options to your question. Ultimately it is up to you which is best for your situation. However, here are some thoughts on how you can choose between them:
- Test the method via the public interface
In your case as you mention you can call calculate
with the correct configuration to execute calculateByA
. This I believe is the best approach. The code has been structured to mean that the calculate
is the public interface by which calculateByA
is accessed. This means that your test will alert people to issues when this behaviour changes. Which in turn means the user of the class will experience a change in behaviour.
- Change the definition of to protected
As you mention, this will then allow you to call calculateByA
from other classes in the same package including unit test classes. This is certainly an approach that will allow for easy and independent unit testing of calculateByA
. However, I don't like this, simply because there is a reason you only want access via the calculate
function and by changing the access it is tempting for other classes in the same package to call calculateByA
directly.
- Use reflection to invoke private method directly
There are a number of technologies that allow you to invoke a private method directly in tests. I won't repeat the excellent answer from by @Tiemo Vorschütz which goes into the details of how to do this. However, this would be my last resort. Simply tests with reflection are more brittle and increase the cost of maintenance of the test suite.