I want to implement package with optimal encapsulation, but test it. How can I do package-private members of one package visible for other one (friendly) package only?
-
1I don't think that's possible. Better to just have getters. – Zarwan Oct 03 '16 at 03:02
-
1First, tests are usually put in the same package as the class under test. Second--don't inspect internal state. Make sure that the class correctly implements its API, but implementation details generally shouldn't be tested directly. – chrylis -cautiouslyoptimistic- Oct 03 '16 at 03:06
-
@Zarwan, In .NET I can mark assembly with `[InternalsVisibleTo("Tests")]` for solve this problem. I can't find barriers for equivalent feature in Java, because it is reflectable too. – Valentyn Zakharenko Oct 03 '16 at 03:13
-
1You could use Reflection to change the accessibility, but I wouldn't recommend that. – Pinkie Swirl Oct 03 '16 at 03:15
-
1Your question embodies a contradiction in terms. – user207421 Oct 03 '16 at 03:16
2 Answers
Yes, it can be done. Kind of...
package private stuff is visible to other classes in the same package, but not necessarily the same directory.
You can declare a class as being in the same package but place it under another directory structure (eg your test code) or even within another project.
You mentioned testing, so I assume you want to "see" this stuff in your tests. Just define your test classes as being in the same package (not the same directory) as your production code.

- 412,405
- 93
- 575
- 722
-
I made project of tests and used the same package name for it, and had success. It is works! I think this way is conceptual right because unit tests is just development tool, they can be used as package extention, but excluded from final product. – Valentyn Zakharenko Oct 03 '16 at 03:52
By definition package-private members are not visible to classes outside the package. This would suggest you are trying to do something you shouldn't, even though you are testing.
You could work around it with a getter, or reflection, but I'd first look at whether you need to access such a member. If it's internal state, you shouldn't be testing it. If it's not, then a getter may be appropriate. Or put your tests in the same package (but possibly stored in a different directory tree).

- 11,641
- 5
- 47
- 65