In this post we’re going to see the minimal required code to get started with Spring Boot and JUnit.
This example can be considered as a start point for creating the Test Automation Framework if you choose Java, JUnit, Spring Boot and Maven as your tech stack.
Spring Boot and JUnit Maven dependencies
To make Spring Boot and JUnit work together you have to setup your
pom.xml you need to set spring-boot-starter-parent as a
At the moment the current version of Spring Boot is 2.0.1.RELEASE.
Also you need to include 2 Spring Boot starters: spring-boot-starter, spring-boot-starter-test.
Spring Boot application class with main method
Just create that JUnitWithSpringBootApplication class with SpringBootApplication annotation in your highest level main (not test) package and forget about it.
SpringBootTest. Spring Boot + JUnit test class
The JUnit test class is the class that contains your test methods. To make JUnit test class work with Spring Boot you should add
@SpringBootTest annotations to the test class.
Now you can use @Autowire, @Value or any other features that Spring Boot gives you. You’re now able to inject already predefined Spring Boot beans or your own beans that you might want to create.
@Value annotation and application.properties
Let’s check if Spring Boot actually works. Create
application.properties file in the test
resources folder and add a parameter
Now we’re going to check if we’re able to inject that into our JUnit tests with Spring Boot.
If you do all right and the parameter
application.properties is successfully injected then
springBootJUnitParameterInjectedTest should pass
@Autowired and @Bean annotations
Now we’re going to verify that we’re able to create a Spring bean (
@Bean) and inject it (
Finally our Spring Boot + JUnit test class is going to be
and if we do all right then all tests should pass. That means we were able to inject Spring Boot beans into JUnit tests.
Spring Boot + JUnit Github Gists:
You may also find these posts interesting: