Unit Testing Using Spring Boot

Learn how to write a test using the @SpringBootTest annotation and why it should not be used for unit testing.

When we create an application using Spring Boot, we get the springboot-starter-test dependency that comes with Mockito and AssertJ as testing libraries. We also automatically get a test file with the @SpringBootTest annotation.

Unit testing should not be done using Spring Boot. The main purpose of unit testing is to test a method or class. However, @SpringBootTest loads the entire context, which makes the test lengthy and defeats the purpose of unit testing. This feature of Spring Boot should be used in integration testing where we test across multiple layers.

The purpose of this lesson is only to show how a unit test can be written using the @SpringBootTest annotation.

spring-boot-starter-test dependency

The pom.xml file of a Spring Boot project has the following dependency on spring-boot-starter-test:


We will begin by creating a JUnit test case in src/test/java, taking care that we match the package structure of the class being tested with the test file. The test is called RecommenderImplementationSpringBootTest as we want to show how to use test features provided by Spring Boot. We will rename the test method testRecommendMovies().

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.