Noisy NPE warning in Test classes
已回答
I have numerous test cases that do something like this:
assertThat(foo.getBar().getBaz()).isEqualTo(whatever);
But because this is the first access of bar I get the following warning:
Method invocation 'getBar()' may produce 'NullPointerException'
I'm perfectly happy with test code throwing an NPE, after all, if it does, the test will fail. And that is what I want.
I don't want to apply the suggested fix of sticking Objects.requireNonNull() around it all as it just muddies the code. It is just a test after all. I also don't want to disable the warning across the project because it is useful in the main codebase. Is there a way to disable it just for tests? Much like the way you don't get warned about using property injection with @Autowired in a JUnit test. But you do get warned outside of tests.
请先登录再写评论。
Hello, you may suppress the inspection for the whole test class or disable the inspection for the assert statements:
Please tell if it solves the issue? Thank you
Thanks Olga.
Is that the correct inspection? This isn't a constant, it is a maybe :) Though I can't find the actual one in the settings.
In terms of suppressing the inspection, I was hoping to be able to do it for all tests rather than one at a time.
Thanks.
Hello,
Yes, the inspection that is responsible for the NPE warning is Java | Probable bugs | Constant conditions & exceptions. Can you please check its behavior with "Ignore assert statements" option enabled? Thank you
Thanks Olga.
It didn't make any difference, it still had the yellow highlight against the lines that look like this.
Hello,
If possible can you please create an issue with the little sample project here: https://youtrack.jetbrains.com/issues/IDEA
Thank you
Hello!
In the last version there is no such option in the menu as
Java | Probable bugs | Constant conditions & exceptions.
Can you pls tell what is the new menu for that?
Smuryginim
Starting with IntelliJ IDEA 2022.3, "Constant Conditions & Exceptions" inspection has been split into two separate inspections:
1. "Constant Values"
2. "Nullability and data flow problems"
Thank you. But I can't find the option to disable null checks syntax highlight in test code in assert statements.
Is it possible?
Hello, I suggest you to disable all
Probable bugs
inspections, as they are useful when you work on normal project files but not under test, since these inspections are not 100% certain that there will be bugs, just some suggestions.So far it's not possible to disable some inspections only in some methods. You may create a feature request at https://youtrack.jetbrains.com/newIssue?project=IDEA .
To disable the NPE warning specifically for test sources, you can adjust the inspection settings:
Preferences/Settings
→Editor
→Inspections
.Probable bugs
section.Please check if this helps, if not, please share the sample project file by uploading it to https://uploads.jetbrains.com/ and share the upload ID here.