ParameterResolver extension in JUnit - Build an Automation Script
import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.api.extension.ParameterContext; import org.junit.jupiter.api.extension.ParameterResolver; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; // Custom object to be injected class CustomObject { private final String value; public CustomObject(String value) { this.value = value; } public String getValue() { return value; } } // ParameterResolver implementation class CustomObjectParameterResolver implements ParameterResolver { @Override public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) { return parameterContext.getParameter().getType() == CustomObject.class; } @Override public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) { return new CustomObject("InjectedValue"); } } @ExtendWith(CustomObjectParameterResolver.class) public class CustomObjectParameterResolverTest { @Test void testInjectedCustomObject(CustomObject customObject) { assertNotNull(customObject, "CustomObject should be injected and not null"); assertEquals("InjectedValue", customObject.getValue(), "CustomObject value should match the injected value"); } }
The code defines a CustomObject class with a simple string property.
The CustomObjectParameterResolver class implements JUnit 5's ParameterResolver interface. It overrides supportsParameter to check if the parameter type is CustomObject. It overrides resolveParameter to return a new CustomObject instance with a fixed value.
The test class CustomObjectParameterResolverTest is annotated with @ExtendWith to register the resolver. The test method testInjectedCustomObject accepts a CustomObject parameter, which JUnit injects automatically using the resolver.
Assertions check that the injected object is not null and that its value matches the expected string. This confirms the ParameterResolver works correctly.
Now add data-driven testing by injecting different CustomObject instances with different values for three test runs