Spring Boot – Access Spring ApplicationContext in JUnit Tests

This post shows how to access Spring ApplicationContext object in JUnit tests.


Stuff used in this post.

  • Java 8 (JDK)
  • IntelliJ IDEA Ultimate 2016.3
  • Spring Boot 1.5.6.RELEASE

A Simple @Component

We created an “empty” class annotated with @Component. The idea is simply to let Spring load that bean and test if indeed it was instantiated by Spring using JUnit.

JUnit Test

To test out ImportantBean, first step retrieve the Spring ApplicationContext object. This is done by using @Autowired and 2 class-level annotations:

Here is the rest of the JUnit class:

Notice we @Autowired ApplicationContext and that is it!


Download the codes



Karl San Gabriel

Karl San Gabriel

Java and Enterprise Technologies Expert