How can we test a package-private class?

I am reading a book Effective Jave, in Item 13: Minimize the accessibility of classes and members, she mentioned that:

To make testing easier, you might be tempted to make a class, interface, or member available. This is good to a certain extent. it is permissible to make the private member of an open class package private to check it, but it is unacceptable to increase the availability exceeding it. In other words, it is not acceptable to make a class, interface, or part of a part of exported API packages to facilitate testing.

I know that we need to encapsulate members, hide information from clients, we can test them by accessing the class using setters and getters, but How can I understand if I can make the class private, if so, how can I check it?

+4
source share
2 answers

This basically means that your tester class should be in the same package as your test class. This will allow your tested class and all members and methods protected by the package available to your testing class. Classes can be located under different roots: your test class can be under src/myrootpackage.first.second.MyClass, and your test class can be undertest/myrootpackage.first.second.MyClass.Tester

+2
source

I assume that the author means that instead

package my.package;

class TestableClass {
     private String property;
}

You can change the visibility to

package my.package;

class TestableClass {
    String property;
}

In the second implementation, you can access the property from a test in a package my.package, for example

package my.package;

class TestableClassTest {
    // ...
}

- , protected.

+1

Source: https://habr.com/ru/post/1669859/


All Articles