Spring Boot – Starter Test
Last Updated :
07 Mar, 2025
Spring Boot is built on top of the spring and contains all the features of spring. It is becoming a favorite of developers these days because of its rapid production-ready environment, which enables the developers to directly focus on the logic instead of struggling with the configuration and setup. Spring Boot is a microservice-based framework, and making a production-ready application in it takes very little time. Some of the features of Spring Boot are given below:
- It allows avoiding heavy configuration of XML, which is present in spring.
- It provides easy maintenance and creation of REST endpoints.
- It includes an embedded Tomcat server.
- Deployment is very easy; war and jar files can be easily deployed in the tomcat server
Introduction to Testing in Spring Boot
Spring Boot provides a starter dependency, spring-boot-starter-test, which includes essential testing libraries such as JUnit 5 (Jupiter), AssertJ, Mockito, and Testcontainers for integration testing.
This article demonstrates how to set up and run tests effectively using modern Spring Boot 3.x practices.
Example
In this example, we will create a spring boot project and add spring-boot-starter-test dependency, and run predefined tests of the application class.
Step-by-Step Implementation
Step 1: Create a Spring Boot Project
In this step, we will create a spring boot project. For this, we will use Spring Initializr and once we create the project we will import it into our Eclipse IDE.
- Spring Boot Version: 3.x
- Java Version: 17
- Dependencies: Spring Web, Spring Boot Starter Test (This dependency comes inside the Spring Web dependency)
Below is the screenshot is given for the spring boot project configuration. Once you are done with your configuration click on Generate button, it will automatically generate a zip file for our project.
Step 2: Import Spring Boot Project in Eclipse IDE
Once we will have the zip file for our project we will import it into our IDE. For this Go to File > Import.
After this go to Maven Projects > Existing Maven Project then click on the Next button.
Now we need to browse to the project location and select the project directory and click on the Finish button.
Step 3: Adding Dependencies
Once we will create a spring boot project and import it into our IDE, we will find there is a file pom.xml that holds the dependencies of the project. In the pom.xml, there is already a dependency is present for the spring boot starter test.
Note: Ensure that the spring-boot-starter-test dependency is present in your pom.xml.
XML
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- Testcontainers for integration testing -->
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
Above, we can look for spring-boot-starter-test dependency, there is <scope>test</scope>. It means the scope of the test is only up to the development and test mode.
- JUnit 5 (Jupiter) is included by default in Spring Boot 3.x.
- Testcontainers is added for integration testing.
Once the application is developed and bundled and packaged, all the test scope dependencies are ignored.
Step 4: SpringBootStarterTestApplicationTests Class
After the dependencies are added and the application is successfully built. We can look is our project root path, we will find classes for the test. In our case it is named “SpringBootStarterTestApplicationTests“. It is present at the src/test/java root path.
Step 5: Running the Test Class
In this step, we will run our SpringBootStarterTestApplicationTests class. The default test class contains a simple test method annotated with @SpringBootTest and @Test. Below is the predefined code for our test class:
Java
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
// @SpringBootTest annotation is
// used to mark a standard Spring test
@SpringBootTest
class SpringBootStarterTestApplicationTests {
// @Test annotation marks a
// method as a test method
@Test
void contextLoads() {
}
}
In the above, spring boot by default has provided two annotations:
- @SpringBootTest: This annotation is marked over the test class that runs the standard spring boot tests. The @SpringBootTest annotation has the following features over the Spring Test Context framework.
- If @ContextConfiguration(loader=””) is explicitly defined, It uses the default SpringBootContextLoader.
- It supports various WebEnvironment modes (e.g., MOCK, RANDOM_PORT)
- If an application uses a web server for a web test then it automatically registers for a TestRestTemplate or WebTestClient bean.
- It provides facilities for application arguments to be defined using the args attribute.
- @Test: This annotation marks a method as the test method.
Step 6: Output
In this step, we will run our application.
- To run the test, right-click the test class and select Run As > JUnit Test.
- The contextLoads() test will execute, verifying that the application context starts successfully.
Additional Best Practices
1. Using @TestInstance(Lifecycle.PER_CLASS)
Use @TestInstance(Lifecycle.PER_CLASS) to create a single instance of the test class for all test methods.
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.TestInstance.Lifecycle;
@TestInstance(Lifecycle.PER_CLASS)
class MyTestClass {
// Test methods
}
2. Using @AutoConfigureMockMvc for Web Tests
Use @AutoConfigureMockMvc for efficient testing of Spring MVC controllers.
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.web.servlet.MockMvc;
@SpringBootTest
@AutoConfigureMockMvc
class MyControllerTest {
@Autowired
private MockMvc mockMvc;
// Test methods using mockMvc
}
3. Using Sliced Tests for Better Performance
Use sliced tests like @WebMvcTest and @DataJpaTest to test specific layers of the application.
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.web.servlet.MockMvc;
@WebMvcTest(MyController.class)
class MyControllerTest {
@Autowired
private MockMvc mockMvc;
// Test methods
}
4. Testcontainers for Integration Testing
Use Testcontainers for integration testing with real databases and services.
import org.junit.jupiter.api.Test;
import org.testcontainers.containers.PostgreSQLContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
@Testcontainers
class MyIntegrationTest {
@Container
static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>(“postgres:13”);
@Test
void testDatabaseConnection() {
// Test logic
}
}
5. AssertJ for Fluent Assertions
Use AssertJ for more readable assertions.
import static org.assertj.core.api.Assertions.assertThat;
@Test
void testAssertions() {
String result = myService.doSomething();
assertThat(result).isEqualTo(“expectedValue”);
}
6. Mockito for Mocking Dependencies
Use Mockito for mocking dependencies in unit tests.
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
@ExtendWith(MockitoExtension.class)
class MyServiceTest {
@Mock
private MyRepository myRepository;
@InjectMocks
private MyService myService;
@Test
void testServiceMethod() {
when(myRepository.findById(anyLong())).thenReturn(Optional.of(new MyEntity()));
// Test logic
}
}
Similar Reads
Spring Boot MockMVC Example
Automated testing plays a vital role in the software industry. In this article, let us see how to do the testing using MockMvc for a Spring Boot project. To test the web layer, we need MockMvc and by using @AutoConfigureMockMvc, we can write tests that will get injected. SpringBootApplication is an
4 min read
Spring Boot Integration With PostgreSQL as a Maven Project
PostgreSQL is a user-friendly versatile RDBMS. This article lets us see how to integrate Spring Data JPA with PostgreSQL. There are some conventions to be followed while using PostgreSQL. We will cover that also. Working with PostgreSQL We can easily create databases and tables in that. The below sc
3 min read
Spring Boot JPA Sample Maven Project With Query Methods
In this article, let us see a sample maven project in Spring Boot JPA with Query methods. Spring Boot + JPA removes the boilerplate code and it will be enhanced much if we use query methods as well. Let us discuss this project with MySQL Connectivity for geeksforgeeks database and table name as "Con
6 min read
Spring Boot - Service Class Example for Displaying Response Codes and Custom Error Codes
Sometimes the error or status messages in webpages would be different from the default error message thrown by Tomcat (or any other server). An important reason for this is websites want to look unique in their approach to their users. So, a customized page for displaying status codes is always bett
6 min read
Spring Boot - Create a Custom Auto-Configuration
Usually, we might be taking a maven project or grade project for Spring Boot related projects. We will be adding the dependencies in pom.xml (in case of a maven project). In a spring application, Spring Boot auto-configuration helps to automatically configure by checking with the jar dependencies th
4 min read
Spring Boot - Consume Message Through Kafka, Save into ElasticSearch, and Plot into Grafana
In this article, we are going to make a program to produce some data using Kafka Producer which will consume by the Kafka Consumer and save into the elastic search DB, and later on, plot that JSON data into the Grafana dashboard. Start with configuring all the required software and tool. Requirement
7 min read
How to Implement AOP in Spring Boot Application?
AOP(Aspect Oriented Programming) breaks the full program into different smaller units. In numerous situations, we need to log, and audit the details as well as need to pay importance to declarative transactions, security, caching, etc., Let us see the key terminologies of AOP Aspect: It has a set of
10 min read
Spring Boot - AOP(Aspect Oriented Programming)
The Java applications are developed in multiple layers, to increase security, separate business logic, persistence logic, etc. A typical Java application has three layers namely they are Web layer, the Business layer, and the Data layer. Web layer: This layer is used to provide the services to the e
4 min read
Spring Boot - Cache Provider
The Spring Framework provides support for transparently adding caching to an application. The Cache provider gives authorization to programmers to configure cache explicitly in an application. It incorporates various cache providers such as EhCache, Redis, Guava, Caffeine, etc. It keeps frequently a
6 min read
Spring Boot - AOP Around Advice
Aspect-oriented programming(AOP) as the name suggests uses aspects in programming. It can be defined as the breaking of code into different modules, also known as modularisation, where the aspect is the key unit of modularity. Aspects enable the implementation of crosscutting concerns such as transa
6 min read