I have a junit test suite which uses some AutoCloseable
resources, which I take care of closing after all the tests has been executed using org.junit.jupiter.api.AfterAll
annotation, see the example:
class Tests {
static MyCloseable[] myCloseables = new MyCloseable[3];
static class MyCloseable implements java.lang.AutoCloseable{
public void close(){}
public void doStuff(){}
}
@BeforeAll
static void setup() {
for (int i = 0; i < myCloseables.length; ++i){
myCloseables[i] = new MyCloseable();
}
}
@Test
void test1() {
assertDoesNotThrow(myCloseables[0]::doStuff);
}
@Test
void test2() {
assertDoesNotThrow(myCloseables[0]::doStuff);
}
@AfterAll
static void cleanUp() {
for (MyCloseable myCloseable : myCloseables) myCloseable.close();
}
}
In the for loop body of static void setup()
method IntelliJ gives the following warning:
'MyCloseable' used without 'try'-with-resources statement
But my test is logically correct, I take care of closing the resources afterwards. Is there some way of suppressing / ignoring the code inspection only for the specific line it complains about?
You can use // noinspection resource
on the line IntelliJ complains about, like this:
@BeforeAll
static void setup() {
for (int i = 0; i < myCloseables.length; ++i){
// noinspection resource
myCloseables[i] = new MyCloseable();
}
}
with // noinspection <inspection_group_name>
you can tell IntelliJ to not warn about all the problems included in that <inspection_group_name>
. For instance, in the case of your question, you can see from here https://www.jetbrains.com/help/inspectopedia/Java-Resource-management.html that AutoCloseable used without 'try'-with-resources
is listed in the "Resource management" inspection group, hence // noinspection resource will silence the warning for it.
Unfortunately there is no complete problem -> inspection_group_name mapping available, but you can find some inspection group names in this SO answer: https://stackoverflow.com/a/56857378/12037019