Dependency injection

The ParameterResolver extension provides dependency injection at method level. In this example, we can see how an argument is injected in the test method with a custom implementation of ParameterResolver called MyParameterResolver. Following the code, we can see that this resolver will simply inject hard-coded String parameters with the value my parameter:

package io.github.bonigarcia;

import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.ParameterContext;
import org.junit.jupiter.api.extension.ParameterResolutionException;
import org.junit.jupiter.api.extension.ParameterResolver;

public class MyParameterResolver implements ParameterResolver {

@Override
public boolean supportsParameter(ParameterContext parameterContext,
ExtensionContext extensionContext)
throws ParameterResolutionException {
return true;
}

@Override
public Object resolveParameter(ParameterContext parameterContext,
ExtensionContext extensionContext)
throws ParameterResolutionException {
return "my parameter";
}

}

Then, this parameter resolver can be used in a test, declaring it as usual using the annotation @ExtendWith:

package io.github.bonigarcia;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;

public class DependencyInjectionTest {

@ExtendWith(MyParameterResolver.class)
@Test
public void test(Object parameter) {
System.out.println("My parameter " + parameter);
}
}

Finally, if we execute this test (for example using Maven and the command line), we can see how the injected parameter is logged in the standard output:

Output of dependency injection extension example
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.79.206