Fix “AutoCloseable Used Without Try-With-Resources” Warning in JUnit with Mockito

Overview

When writing unit tests using Mockito in JUnit 4 or JUnit 5, you might encounter the warning:

AutoCloseable used without try-with-resources statement.

This warning typically appears when using MockitoAnnotations.openMocks(this) without properly managing the returned AutoCloseable resource. This article explains why the warning occurs and how to fix it using best practices.

Why the Warning Appears

In Mockito 3 and above, the method MockitoAnnotations.initMocks(this) is deprecated and replaced by:

MockitoAnnotations.openMocks(this);

This method returns an AutoCloseable instance, which should be closed after test execution. If not handled correctly, your IDE or build tool may show the warning.

How to Fix It

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 eliminate the warning, follow these steps:

Step 1: Declare a Closeable Field

private AutoCloseable closeable;

Step 2: Initialize in @Before or @BeforeEach

JUnit 4:

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

JUnit 5:

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

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

Step 3: Close in @After or @AfterEach

JUnit 4:

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

JUnit 5:

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

Why This Matters

Properly managing resources in unit tests ensures:

  • Cleaner test lifecycle
  • No memory/resource leaks
  • Compatibility with newer versions of Mockito
  • Elimination of IDE or compiler warnings

Summary

To fix the “AutoCloseable used without try-with-resources” warning:

  • Use MockitoAnnotations.openMocks(this) correctly.
  • Store the returned AutoCloseable instance.
  • Close it after test execution using closeable.close().

This small change keeps your test code clean, modern, and warning-free.

Share

Related posts

No comments

Leave a comment