Testing / JUnit6 Interview Questions
What is the @AutoClose extension and how does it simplify resource management in JUnit 6?
The @AutoClose annotation (introduced in JUnit 5.11 and fully supported in JUnit 6) automatically calls close() on fields implementing AutoCloseable at the end of the test lifecycle, eliminating the need for @AfterEach/@AfterAll teardown methods for simple resource cleanup.
import org.junit.jupiter.api.AutoClose; class AutoCloseDemo { // Closed after each test method (instance-scoped) @AutoClose private final Connection db = DriverManager.getConnection(TEST_DB_URL); // Closed once after all tests (static = class-scoped) @AutoClose private static final HttpClient httpClient = HttpClient.newHttpClient(); @Test void queryUsers() throws SQLException { // db is open and ready; closed automatically after this test try (PreparedStatement ps = db.prepareStatement("SELECT * FROM users")) { ResultSet rs = ps.executeQuery(); assertTrue(rs.next()); } } @Test void callExternalApi() throws Exception { // httpClient is open; closed once after all tests complete HttpResponse<String> resp = httpClient.send( HttpRequest.newBuilder(URI.create("https://api.test.com")).build(), HttpResponse.BodyHandlers.ofString() ); assertEquals(200, resp.statusCode()); } } // No @AfterEach or @AfterAll needed for these resources! // Equivalent JUnit 5 code (before @AutoClose): class JUnit5Equivalent { private Connection db; @BeforeEach void setUp() throws SQLException { db = DriverManager.getConnection(TEST_DB_URL); } @AfterEach void tearDown() throws SQLException { if (db != null) db.close(); // <-- boilerplate eliminated by @AutoClose } }
More Related questions...