How to use VisibleForTesting for pure JUnit tests

I am using pure JUnit4 java tests on my clean java files in my project, but I cannot find a way to use @VisibleForTesting explicitly without doing public publishing.

Example:

@VisibleForTesting public Address getAddress() { return mAddress; } 

The method must be public so that it is "publicly available" for the tests, but in this case, the annotation does not make sense? why not just use a comment if the annotation does nothing?

+19
java android junit junit4 android-testing
source share
3 answers

According to the documentation for Android:

If you wish, you can specify what visibility should have been if not for testing; this allows tools to catch unintended access from production code.

Example:

@VisibleForTesting (otherwise = VisibleForTesting.PRIVATE) public address getAddress ()

+16
source share

Make the package-private method and the test will be able to see it if the test is in the corresponding test package (the same package name as the production code).

 @VisibleForTesting Address getAddress() { return mAddress; } 

Also consider code refactoring, so you donโ€™t need to explicitly check the private method, try checking the behavior of the open interface. Code that is difficult to verify may indicate that production code can be improved.

An annotation point is its agreement and can be used in the analysis of static code, while a comment cannot be.

+37
source share

The @VisibleForTesting annotation is used in package methods in Guava and is not part of the JUnit API. An annotation is simply a tag indicating that a method can be tested. It does not even load in the JVM.

+2
source share

All Articles