Reputation: 311
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!
Upvotes: 3
Views: 5894
Reputation: 426
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
Upvotes: 1
Reputation: 311
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.
Upvotes: 2
Reputation: 549
Try to add the following annotation to your class SampleIT
:
@RunWith(SpringRunner.class)
Upvotes: 8