Software Development

Spring Boot – Access Spring ApplicationContext in JUnit Tests

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

Requirements

Stuff used in this post.

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

A Simple @Component in Spring Boot

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.

[wp_ad_camp_1]

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:

[wp_ad_camp_2]

Notice we @Autowired ApplicationContext and that is it!

Testing

[wp_ad_camp_3]

Download the codes

https://github.com/Turreta/Spring-Boot-Access-Spring-ApplicationContext-in-JUnit-Tests

[wp_ad_camp_4]

You Might Also Like