'assertThat' causes 'assertions should not be used in production code'

Please provide

  • Operating system: Mac OSX
  • IDE name and flavor/env: IntelliJ
  • SonarLint plugin version: 6.7.0.45926
  • Is connected mode used: Yes
    • Connected to SonarCloud or SonarQube (and which version): SonarQube

And a thorough description of the problem / question:

Sonar is incorrectly identifying a test module as being production code. As such it complains about

Assertions should not be used in production code
 
Bug
 
Major
java:S5960
 
Assertions are intended to be used in test code, but not in production code. It is confusing, and might lead to ClassNotFoundException when the build tools only provide the required dependency in test scope.
In addition, assertions will throw a sub-class of Error: AssertionError, which should be avoided in production code.
This rule raises an issue when any assertion intended to be used in test is used in production code.
Supported frameworks:
 - JUnit
 - FestAssert
 - AssertJ
Note: this does not apply for assert from Java itself or if the source code package name is related to tests (contains: test or assert or junit).

If I rename my package to include test or if I switch over to a SpringFramework assertion the issue goes away. But the test in question has a @Test annotation. It seems artificial to rename or switch assertions purely due to a Sonar limitation.

Is there another workaround?

Hi,

In IntelliJ IDEA, we are relying on IDE source folder classification to know if a file is a test or production code. Can you double check in your project settings if the folder containing your source file is a test folder?

It does not consider the project to be Test Source. My problem is that our project is defined by Maven. Won’t any changes I make here disappear? Is there a Maven setting to tell IntelliJ that this is test code?

Maven has a pretty clear distinction between test and production code. You should put your test code in src/test/java, and IntelliJ will automatically consider it as a test folder.
If you are using a less common layout, please share the details (like do you intentionally put your production and test code in src/main/java? How do you make it work in Maven?)

This works. The module in question is a standalone test jar. It was created with src/main/java rather than src/test/java. However I don’t have a problem switching it over. In fact I tested that before, but it did not resolve the issue. Turns out I needed to refresh the IntelliJ project for the switch to appear.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.