‘AutoCloseable’ used without ‘try’-with-resources statement

Problem

The warning message ‘AutoCloseable’ used without ‘try’-with-resources statement may appear in your Junit class(es) when you might have the similar kind of line (MockitoAnnotations.initMocks(this); is replaced in Mockito 3 by MockitoAnnotations.openMocks(this);) as shown below in your Junit class:

Junit 5

@BeforeEach
void init() {
	MockitoAnnotations.openMocks(this);
}

Or

Junit 4

@Before
void init() {
	MockitoAnnotations.openMocks(this);
}

If you use deprecated statement MockitoAnnotations.initMocks(this); in Mockito 2 then you won’t see the above warning message.

Solution

The MockitoAnnotations.openMocks() method returns an instance of AutoClosable which can be used to close the resource once the test is over.

When MockitoAnnotations.openMocks() is called, Mockito will create mocks for fields annotated with the @Mock annotation. It also creates an instance of the field annotated with @InjectMocks and try to inject the mock objects into it automatically.

To fix the warning message and make it disappear you can change as follows:

1. Create a private instance field in your Junit class

private AutoCloseable closeable;

2. For Junit 4 use the following code snippets:

@Before
void init() {
	closeable = MockitoAnnotations.openMocks(this);
}

For Junit 5 use the following code snippets:

@BeforeEach
void init() {
	closeable = MockitoAnnotations.openMocks(this);
}

3. Next close the AutoCloseable instance.

For Junit 4 use the following code snippets:

@After
void destroy() throws Exception {
	closeable.close();
}

For Junit 5 use the following code snippets:

@AfterEach
void destroy() throws Exception {
	closeable.close();
}

Now warning message should disappear from your Junit test class.

Leave a Reply

Your email address will not be published. Required fields are marked *