Who has a solution for that common need.
I have a class in my application.
some methods are public, as they are part of the api, and some are private, as they for internal use of making the internal flow more readable
now, say I want to write a unit test, or more like an integration test, which will be located in a different package, which will be allowed to call this method, BUT, I want that normal calling to this method will not be allowed if you try to call it from classes of the application itself
so, I was thinking about something like that
public class MyClass { public void somePublicMethod() { .... } @PublicForTests private void somePrivateMethod() { .... } }
The annotation above will mark the private method as "public for tests" which means, that compilation and runtime will be allowed for any class which is under the test... package , while compilation and\or runtime will fail for any class which is not under the test package.
any thoughts? is there an annotation like this? is there a better way to do this?
it seems that the more unit tests you write, to more your inforced to break your encapsulation...
Denotes that the class, method or field has its visibility relaxed, so that it is more widely visible than otherwise necessary to make code testable.
Use the TestVisible annotation to allow test methods to access private or protected members of another class outside the test class. These members include methods, member variables, and inner classes. This annotation enables a more permissive access level for running tests only.
By not testing private methods, you are leaving gaps in your testing that may not be discovered until much later. In the case where private method is complex and not easily exercised by a public interface, it should be unit tested.
The common way is to make the private method protected or package-private and to put the unit test for this method in the same package as the class under test.
Guava has a @VisibleForTesting
annotation, but it's only for documentation purposes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With