简体   繁体   中英

Application context is always null

I am using JUnit5, with sureFire version:

<maven.surefire.plugin.version>3.0.0-M5</maven.surefire.plugin.version>

and code

    @ExtendWith(MockitoExtension.class)
    @ContextConfiguration(classes =....ContextConfiguration.class)
    @TestPropertySource({"classpath:application-${env:dev}.properties", "classpath:app-${env:dev}.properties"})
    class TestRunner{
       @Test
       void testService(){
         BeanUtils.getBean(...);
       }
    }


@Service
public class BeanUtil implements ApplicationContextAware {

    private static ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext; // NOSONAR
    }

    /**
     * Use this method to manually autowire Spring Beans into classes that are not managed by Spring.
     *
     * @param beanClass - Class type of the required bean.
     **/
    public static <T> T getBean(Class<T> beanClass) {
        return context.getBean(beanClass);
    }
}

My ContextConfigurationClass has @ComponentScan directed to BeanUtils class, but the ApplicationContext is always null, not autowired.

I am using @ExtendWith(MockitoExtension.class) cuz i am also mocking in the test.

What JUnit5 extension do i need to use in order to init it?

You should use SpringExtension .

You could also check this post to understand the differences between MockitoExtension and SpringExtension

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM