javaandroidjunitjunit4android-testing

How to use VisibleForTesting for pure JUnit tests


I´m running pure JUnit4 java tests over my pure java files on my project but I can't find a way to use @VisibleForTesting clearly without making the thing manually public.

Ex:

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

The method has to be public to let it be "public" to tests, but in that case the annotation doesn't make sense right? why not just use a comment if the annotation will not do nothing?


Solution

  • 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:

    @VisibleForTesting
    protected Address address() {
      return mAddress;
    }
    

    Kotlin:

    @VisibleForTesting
    internal fun address(): Address {
      return address;
    }