How to use VisibleForTesting for pure JUnit tests How to use VisibleForTesting for pure JUnit tests android android

How to use VisibleForTesting for pure JUnit tests


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

@VisibleForTestingAddress getAddress() {  return mAddress;}

Also consider refactoring your code so you don't need to explicitly test a private method, try testing the behaviour of a public interface. Code that is hard to test can be an indication that improvements can be made to production code.

The point of an annotation is that its convention and could be used in static code analysis, whereas a comment could not.


According to the Android docs:

You can optionally specify what the visibility should have been if not for testing; this allows tools to catch unintended access from within production code.

Example:

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


The Tag itself helps with the linter to identify unwanted access.

To lower the risk of use it directly, add this methods as internal in Kotlin or protected in Java instead of public and with that only the tests or classes that are in the same package will be able to access that method.

Java:

@VisibleForTestingprotected Address address() {  return mAddress;}

Kotlin:

@VisibleForTestinginternal fun address(): Address {  return address;}