Created
November 11, 2018 10:49
-
-
Save chermehdi/22f266e9225f5b6e9db55a40ba3a35c4 to your computer and use it in GitHub Desktop.
Extent your JUnit 5 tests with dependency injection enabled test methods with the help of CDI
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class InjectionExtension implements ParameterResolver { | |
private SeContainer container; | |
/** | |
* boot the CDI context | |
*/ | |
public InjectionExtension() { | |
container = SeContainerInitializer.newInstance().initialize(); | |
} | |
/** | |
* determines weather we can inject all the parameters specified in the test method | |
*/ | |
@Override | |
public boolean supportsParameter(ParameterContext parameterContext, | |
ExtensionContext extensionContext) throws ParameterResolutionException { | |
Method method = (Method) parameterContext.getDeclaringExecutable(); | |
Class<?>[] types = method.getParameterTypes(); | |
return Arrays.stream(types).allMatch(type -> container.select(type).isResolvable()); | |
} | |
/** | |
* resolve the return the object to be used in the test method | |
*/ | |
@Override | |
public Object resolveParameter(ParameterContext parameterContext, | |
ExtensionContext extensionContext) throws ParameterResolutionException { | |
int paramIndex = parameterContext.getIndex(); | |
Method method = (Method) parameterContext.getDeclaringExecutable(); | |
Parameter param = method.getParameters()[paramIndex]; | |
return container.select(param.getType()).get(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment