简体   繁体   中英

Why is Spring @Autowired ApplicationContext null in integration test?

I'm still new to Spring and have looked at similar questions on stack but couldn't identify an answer from what I've read.

I'm receiving an NPE when I call my applicationContext variable, which means the bean must not have been created or injected correctly. Here is the relevant portion of my program.

@SpringBootTest
@ContextConfiguration(classes = TestConfig.class)
public class SampleIT {

    @Autowired
    private ApplicationContext applicationContext;

    @Test
    public void sampleMethod() throws Exception {

        //NPE below
        String[] allBeanNames = applicationContext.getBeanDefinitionNames();

        //more logic 

I'm trying to get the ApplicationContext instance to debug why other beans are null from my config, so this all must be because of a basic flaw in my understanding of how ApplicationContext is setup and beans from it are injected. Any help is very much appreciated!

Try to add the following annotation to your class SampleIT :

@RunWith(SpringRunner.class)

If you are using Junit in version 4, You have to use @RunWith(SpringRunner.class), If you are using Junit version 5, You have to use @ExtendWith(SpringExtension.class).

Additionally if you are using Mockito You can use @ExtendWith(MockitoExtension.class) etc.

I highly recommend read documentation about @SpringBootTest annotation in this link @SpringBootTest

Answering my own question now. Importing org.junit.jupiter.api.Test instead of org.junit.Test will cause Junit5 to be used. This will allow Junit to work with Spring without the @RunWith(SpringRunner.class) annotation. There are still remnants of Junit4 left in the codebase I'm working in, so this is a quick fix before completely moving to Junit 5.

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