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