javaunit-testingintellij-ideajunitvisibility

IntelliJ: get a warning if I call a method annotated with @VisibleForTesting


I have the following use case:

I want to Unit-test a private method (I really want to). Now, there are different approaches, but I want to choose the approach "make the method package private".

In Guava, there's an annotation called @VisibleForTesting. What I want to do is: Whenever this method is called from another class (in the same package, of course), regardless of it's a subclass of this class or not, display a warning like "Hey dude, the method you want to call is marked with @VisibleForTesting, are you sure you want to call it?".

I played a bit with custom inspections, but with no luck so far. Does anyone have an idea?


Solution

  • There is no need for a custom inspection, the necessary inspection is built in. Go to Setting | Editor | Inspections and enable the inspection JVM languages | Test frameworks | Test-only usage in production code. Then a warning will be reported if members with the @VisibleForTesting annotation are accessed from production code, but not from test code.


    Note: before IntelliJ 2024.1.7 , the inspection could be found under Java | General | Test-only class or method call in production code.