Java, Software Development, Spring Boot

Spring Boot – Access Spring ApplicationContext in JUnit Tests

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.

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.

Here is the rest of the JUnit class that uses the Spring ApplicationContext.

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.


Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.

You Might Also Like