3

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?

Valentyn Zakharenko
  • 2,710
  • 1
  • 21
  • 47

2 Answers2

2

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.

Bohemian
  • 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
1

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).

dave
  • 11,641
  • 5
  • 47
  • 65