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
properly.
In your pom.xml
you need to set spring-boot-starter-parent as a parent
.
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 @RunWith(SpringRunner.class)
and @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
application.properties
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 foo
from 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 (@Autowired
).
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.
Find more posts related to Spring Boot and JUnit by tags Spring Boot and JUnit
Spring Boot + JUnit Github Gists:
You may also find these posts interesting: