This post shows how to access the Spring ApplicationContext object in JUnit tests. Now, why would we want to do that? Well, sometimes, we need to work directly with the ApplicationContext object.
Spring, Java, and Other Requirements
We used the following items for this post. These are for reference only, but similar codes may still work using later versions of Java and Spring Boot.
- Java 8 (JDK)
- IntelliJ IDEA Ultimate 2016.3
- Spring Boot 1.5.6.RELEASE
Spring @Component To Use in JUnit Tests
For this post, we use a Java class, and we annotate it with @Component. The idea is to let the Spring container load that bean and test if Spring instantiated the class in a JUnit test.
1 2 3 4 5 6 7 8 9 | package com.turreta.springboot.applicationcontext.junit; import org.springframework.stereotype.Component; @Component public class ImportantBean { // Intentionally left empty } |
JUnit Test And ApplicationContext
To test out the ImportantBean, we first try retrieving it from the Spring ApplicationContext. However, we need to use two class-level annotations and @Autowired.
1 2 | @RunWith(SpringRunner.class) @SpringBootTest |
Here is the rest of the JUnit class that uses the Spring ApplicationContext.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | package com.turreta.springboot.applicationcontext.junit; ... import org.springframework.context.ApplicationContext; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class ImportantBeanTest { @Autowired private ApplicationContext context; @Test public void aComponent() { Assert.assertTrue(context.getBean(ImportantBean.class) != null); } } |
Notice we use @Autowired with the Spring ApplicationContext and its getBean method in a JUnit test method.
Testing With The Spring ApplicationContext
When we run the JUnit method to test against the Spring ApplicationContext, we get the following output.
As we can see, the JUnit test passed because the codes could retrieve the bean from the ApplicationContext.
Download the codes
The codes for this post are available on GitHub.