Search code examples
javaunit-testingencapsulation

Best practices for accessing private static final values in unit tests


If a private static final value X from a class is needed in a unit test (in a separate package), how should one go about obtaining X? I can think of three options, none of which seems clean to me:

1) Copy X into the test class. I fear that if the source's X is changed, while the test's X is preserved, the unit test would still pass when it should fail.

2) Make X public. I fear this breaks encapsulation. Nonetheless, this is in my opinion the best option given that X is final.

3) Create a public getter for X. This also seems like it's breaking encapsulation if X should only be accessed from the class and unit test.


Solution

  • I would say you don't need to access it. If something is private, then it's used as an implementation detail and should be invisible to the test. You should test the requirements of the class, not the implementation details. Why you ask? Because, over time, the implantation is likely to change (or evolve) while the requirements should be consistent.