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 } }
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
