Injecting Spring beans into a ParameterResolver in JUnit Jupiter

830 Views Asked by At

Trying to get Spring component (DataSource) autowired into JUnit ParameterResolver. But DataSource is not getting injected by Spring.

I have registered the SpringExtension and also provided the context location (aaspire-test-datasource-components.xml) to load the ApplicationContext.

@ContextConfiguration(locations={"classpath:spring-config/aaspire-test-datasource- 
 components.xml"})
@ExtendWith(SpringExtension.class)
public class gdnContextResolver implements ParameterResolver
{   
    @Autowired
    private DataSource dataSource;

    @Override
    public boolean supportsParameter(ParameterContext parameterContext, 
      ExtensionContext extensionContext) throws ParameterResolutionException {
       return parameterContext.getParameter().getType() == gdnContext.class;
    }

    @Override
    public Object resolveParameter(ParameterContext parameterContext, 
     ExtensionContext extensionContext) throws ParameterResolutionException {
     
      try {
        return  SpringBatchJobUtil.createJobExecutionGdnContext(dataSource);
     } catch (Exception e) {            
        throw new ParameterResolutionException(ExceptionUtil.getMessageText(e));
     }    
      
   }
}
1

There are 1 best solutions below

0
On

You cannot register extensions on an extension via @ExtendWith.

In addition, Spring annotations such as @ContextConfiguration cannot be applied to an extension, and you cannot autowire Spring components into an extension.

So, you need to remove the @ExtendWith and @ContextConfiguration declarations, and instead of autowiring the DataSource into a field in your extension you need to use the SpringExtension to retrieve the ApplicationContext for the "current test".

You can achieve the latter in your resolveParameter() implementation as follows.

DataSource dataSource = SpringExtension.getApplicationContext(extensionContext).getBean(DataSource.class);