Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

annotation to make a private method public only for test classes [duplicate]

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

like image 647
Kumetix Avatar asked Aug 02 '11 14:08

Kumetix


People also ask

What does Visiblefortesting annotation do?

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.

How do you make a private method visible in test class?

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.

Should I make private methods public for testing?

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.


1 Answers

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.

like image 199
JB Nizet Avatar answered Oct 14 '22 09:10

JB Nizet