Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 371
Master_Yoda Avatar asked Jun 27 '14 15:06

Master_Yoda


2 Answers

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.

like image 70
Isaiah van der Elst Avatar answered Nov 14 '22 17:11

Isaiah van der Elst


I would go with the third option of yours.

I would create a private static final variable in the test class and assign it with the getter, that gets the value of the private static final value required. This way your value at the test class would have the similar properties as the original values.

I hope this helps.

like image 43
Lohit Avatar answered Nov 14 '22 17:11

Lohit