What is the difference between @TestOnly and @VisibleForTesting in unit test

Viewed 1236

As per my understanding, these annotations used for methods with an access modifier that allows method invocation from another class for unit testing

@VisibleForTesting - com.google.common.annotations.VisibleForTesting
@TestOnly - org.jetbrains.annotations.TestOnly

1 Answers

The first big difference is obviously that it's provided by different projects.

@VisibleForTesting is part of the Google Guava libraries and @TestOnly is part of JetBrains annotations which are associated with JetBrains, the makers of IntelliJ IDEA, among others.

Comparing the JavaDoc of the two shows that they serve basically identical goals: @TestOnly and @VisibleForTesting.

Note that the documentation of both annotations contain a note effectively warning you that the annotation itself does not prevent production code from calling the annotated method. JetBrains suggests the use of static checking tools that support that annotation (one of which is presumably built into IntelliJ IDEA) and Guava suggests the use of external checker tools with an explicit list of forbidden APIs.

tl;dr They indicate effectively the same thing. The decision which one to use depends mostly on which tools you are using to act on them and which one they support. Already using other annotations or classes from one of those packages is another reason to pick one over the other.

Related