Testing / JUnit6 Interview Questions
What is the ParameterResolver extension interface and how do you use it for custom injection?
The ParameterResolver extension interface allows you to inject custom objects into test method parameters, @BeforeEach methods, and constructors. This is the foundation of how MockitoExtension injects @Mock objects and how SpringExtension injects beans.
// Custom ParameterResolver: inject a configured HttpClient public class HttpClientExtension implements ParameterResolver, BeforeEachCallback, AfterEachCallback { private final Map<ExtensionContext, HttpClient> clients = new ConcurrentHashMap<>(); @Override public boolean supportsParameter( ParameterContext paramCtx, ExtensionContext extCtx) { // Only resolve HttpClient parameters return paramCtx.getParameter().getType() == HttpClient.class; } @Override public Object resolveParameter( ParameterContext paramCtx, ExtensionContext extCtx) { // Create and return an HttpClient for this test HttpClient client = HttpClient.newBuilder() .connectTimeout(Duration.ofSeconds(5)) .build(); clients.put(extCtx, client); return client; } @Override public void afterEach(ExtensionContext ctx) { HttpClient client = clients.remove(ctx); if (client != null) client.close(); } } // Usage: @ExtendWith(HttpClientExtension.class) class ApiIntegrationTest { @Test void fetchUsers(HttpClient client) { // injected by extension! HttpResponse<String> resp = client.send( HttpRequest.newBuilder(URI.create("https://api.example.com/users")).build(), HttpResponse.BodyHandlers.ofString() ); assertEquals(200, resp.statusCode()); } }
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...
