Testing: Ensuring Your Code Actually Works
7 min read
Shipping code without tests is like skydiving while trying to sew your parachute on the way down. It is thrilling, but it rarely ends well. We write tests for one simple reason: to verify that our application does what it is supposed to do, so we can sleep soundly on the weekends instead of fixing production crashes at 3:00 AM.
A Quick History Fact: In 1999, NASA's Mars Climate Orbiter burned up in the Martian atmosphere. Why? One engineering team used metric units, and another used imperial units. A simple automated test verifying the outputs could have saved the $125 million mission! 🚀💥
Let's break down how we test applications in the Spring Boot ecosystem, starting from the smallest pieces of logic all the way up to full system simulations.
1. The Testing Pyramid in the Spring Boot Ecosystem 📐
Definition: The Testing Pyramid is a strategy and visual metaphor that groups software tests into three distinct layers based on their scope and execution speed: Unit, Integration, and End-to-End (E2E).
The Problem: Running the entire Spring Boot application (starting the server, connecting to the database, loading all services) takes time. If you run the full app to test every tiny logic change, your test suite will take hours to finish. This destroys developer productivity.
The Solution: We organize our tests into a pyramid to balance speed and confidence.
- The Base (Unit Tests): The majority of your tests. They test a single class or method in complete isolation. They are lightning-fast and do not require Spring Boot to start.
- The Middle (Integration / Slice Tests): A moderate amount of tests. They verify how specific layers (like the Web layer or Database layer) interact with the framework. Slower than unit tests, but faster than starting the whole application.
- The Top (End-to-End / Full Integration): Very few tests. They boot up the entire application along with real databases to ensure everything works together. They are slow but provide the highest confidence.
2. Unit Testing Business Logic: JUnit 5 and Mockito Basics 🛠️
Definition:
- JUnit 5: A testing framework for Java that executes your test methods and reports whether they passed or failed.
- Mockito: A Java library used to generate fake objects (called mocks) for dependencies.
The Problem: You want to test the UserService, which calculates a user's discount. However, the UserService relies on an EmailClient to send a "Welcome" email. If you write a standard test, you will accidentally spam real emails every time the test runs.
The Solution: You use Mockito to intercept the EmailClient and create a dummy version of it. The mock returns pre-configured responses without executing the real email code.
Imagine you are running a restaurant. The customers (HTTP requests) give orders to the waiters (Controllers). The waiters hand the orders to the kitchen staff (Services), who grab ingredients from the pantry (Database). If you want to test the kitchen staff's ability to chop carrots, you do not need the waiter or the actual pantry. You just hand the kitchen staff a raw carrot directly and watch them chop it. This is a unit test: pure, isolated business logic.
Industry Standard Practice
Here is how you test a Spring Service using JUnit 5 and Mockito. We do not load Spring at all here.
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;
import static org.mockito.Mockito.*;
import static org.junit.jupiter.api.Assertions.*;
// 1. Tells JUnit to enable Mockito annotations
@ExtendWith(MockitoExtension.class)
class UserServiceTest {
// 2. Creates a fake, empty version of the database repository
@Mock
private UserRepository userRepository;
// 3. Injects the fake repository into the real service we are testing
@InjectMocks
private UserService userService;
@Test
void shouldReturnVIPStatus_WhenUserPurchasesExceed1000() {
// Arrange: Teach the mock how to behave
User dummyUser = new User("Alice", 1500.0);
when(userRepository.findByUsername("Alice")).thenReturn(dummyUser);
// Act: Call the real business logic
boolean isVip = userService.checkVipStatus("Alice");
// Assert: Verify the result was correct
assertTrue(isVip);
// Verify that the repository was actually called exactly once
verify(userRepository, times(1)).findByUsername("Alice");
}
}3. Slice Testing the Web Layer: @WebMvcTest 🌐
Definition: @WebMvcTest is a Spring Boot annotation that loads only the web components (Controllers, Exception Handlers, Filters) into the application context, ignoring Services and Repositories.
The Problem: Testing a Controller using pure JUnit (like above) is useless because it misses the most important parts of the web layer: HTTP status codes, JSON serialization, and URL routing. But loading the whole database just to check if /api/users returns a 200 OK is overkill.
The Solution: @WebMvcTest spins up a lightweight version of Spring. It uses MockMvc to simulate HTTP requests without actually binding to a network port.
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.context.bean.override.mockito.MockitoBean;
import org.springframework.test.web.servlet.MockMvc;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
// 1. Load ONLY the UserController
@WebMvcTest(UserController.class)
class UserControllerTest {
// 2. MockMvc simulates HTTP requests
@Autowired
private MockMvc mockMvc;
// 3. Provide a fake Service to the Spring Context.
// Note: In Spring Boot 3.4+, use @MockitoBean. For older versions, use @MockBean.
@MockitoBean
private UserService userService;
@Test
void shouldReturnUserJson() throws Exception {
// Arrange
when(userService.getUser("Bob")).thenReturn(new User("Bob", 50.0));
// Act & Assert
mockMvc.perform(get("/api/users/Bob"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.username").value("Bob"))
.andExpect(jsonPath("$.purchases").value(50.0));
}
}4. Slice Testing the Data Layer: @DataJpaTest 💾
Definition: @DataJpaTest is an annotation that configures and tests only the JPA components (Entities and Repositories) of your application.
The Problem: You wrote a custom SQL query using @Query("SELECT u FROM User u WHERE u.active = true"). If you have a syntax error, a mocked unit test will not catch it because mocks do not execute SQL. You need a real database engine to process the query.
The Solution: @DataJpaTest disables full auto-configuration and applies only configuration relevant to JPA tests. By default, it replaces your real database with an incredibly fast, embedded in-memory database (like H2). More importantly, it automatically rolls back transactions at the end of each test, ensuring one test does not corrupt the database for the next one.
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import static org.assertj.core.api.Assertions.assertThat;
// 1. Load only the Data Layer
@DataJpaTest
class UserRepositoryTest {
@Autowired
private UserRepository userRepository;
@Test
void shouldFindActiveUsers() {
// Arrange: Save real data into the in-memory database
User activeUser = new User("Charlie", true);
User inactiveUser = new User("Dave", false);
userRepository.save(activeUser);
userRepository.save(inactiveUser);
// Act: Test the custom query
List<User> result = userRepository.findAllActiveUsers();
// Assert
assertThat(result).hasSize(1);
assertThat(result.get(0).getUsername()).isEqualTo("Charlie");
}
}5. Full Integration Testing: @SpringBootTest and Testcontainers 🐳
Definition:
@SpringBootTest: An annotation that loads the entire Spring Application Context (Web, Service, and Data layers).- Testcontainers: A Java library that supports JUnit tests by spinning up lightweight, throwaway instances of real databases, message brokers, or anything that can run in a Docker container.
The Problem: In-memory databases (like H2) are great, but they behave differently than production databases (like PostgreSQL or MySQL). Your test might pass on H2 but crash in production due to dialect differences. "It worked on my machine" is the famous last words of a developer about to cause an outage.
The Solution: We run full integration tests. Testcontainers boots up a real PostgreSQL Docker container right before your tests start, and destroys it when they finish. Thanks to Spring Boot 3.1+'s @ServiceConnection magic, Spring automatically discovers the container's randomized port and credentials and connects your application to it—zero boilerplate required.
Imagine assembling a car. Unit tests check the spark plugs on a workbench. Slice tests verify the engine turns over. Full integration tests put the fully assembled car on a track, put a driver in it, and see if it actually drives without exploding.
Step 1: Add Boilerplate Dependencies
(Strictly requiring modern Spring Boot 3.1+ conventions)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-testcontainers</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>postgresql</artifactId>
<scope>test</scope>
</dependency>Step 2: Write the Full Integration Test
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.testcontainers.service.connection.ServiceConnection;
import org.springframework.test.web.servlet.MockMvc;
import org.testcontainers.containers.PostgreSQLContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
// 1. Boot the entire application
@SpringBootTest
// 2. Let MockMvc make simulated requests against the fully loaded app
@AutoConfigureMockMvc
// 3. Enable Testcontainers
@Testcontainers
class ApplicationIntegrationTest {
// 4. Start a real PostgreSQL container.
@Container
// 5. Magic Annotation! Automatically overwrites the application.properties
// URL, Username, and Password to point to this temporary Docker container.
@ServiceConnection
static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:15-alpine");
@Autowired
private MockMvc mockMvc;
@Test
void completeUserCreationFlow() throws Exception {
// We are hitting the actual controller, which calls the actual service,
// which saves to the actual PostgreSQL database running in Docker.
String newUserJson = "{\"username\": \"Eve\", \"purchases\": 0.0}";
mockMvc.perform(post("/api/users")
.contentType("application/json")
.content(newUserJson))
.andExpect(status().isCreated());
}
}📚 References & Further Reading
Challenge
Challenge: Write a Web Layer Slice Test
You are provided with the skeletons of a Product DTO, a ProductService interface, a ProductNotFoundException, and a ProductController. The controller has a single GET endpoint /api/products/{id} that retrieves a product.
Your task is to implement the ProductControllerTest class to perform a slice test on the ProductController. This test should verify the controller's behavior in isolation, without loading the entire application context.
Requirements:
- Configure the test class to be a web slice test targeting only the
ProductController. - Inject the necessary beans for performing mock HTTP requests and for mocking the
ProductServicedependency. - Implement the test method
whenGetProductById_withValidId_thenReturnsProduct:- It should mock the
productServiceto return a sampleProductwhen called with a valid ID. - It must perform a GET request to the corresponding endpoint.
- It must assert that the HTTP response status is 200 (OK) and that the JSON response body correctly represents the returned product.
- It should mock the
- Implement the test method
whenGetProductById_withInvalidId_thenReturnsNotFound:- It should mock the
productServiceto throw aProductNotFoundExceptionwhen called with an invalid ID. - It must perform a GET request with the invalid ID.
- It must assert that the HTTP response status is 404 (Not Found).
- It should mock the
Expected result
The final code should be a complete JUnit 5 test class for a Spring Boot controller. Here are the specific requirements for the solution:
Class Annotations: The
ProductControllerTestclass must be annotated with@WebMvcTest(ProductController.class)to specify that this is a slice test focusing on theProductController.Field Annotations:
- The
MockMvc mockMvcfield must be annotated with@Autowiredto inject the bean used for making requests. - The
ProductService productServicefield must be annotated with@MockBeanto replace the actual service with a mock in the application context.
- The
whenGetProductById_withValidId_thenReturnsProductMethod Implementation:- The mock setup should be
when(productService.getProductById(1L)).thenReturn(sampleProduct);. - The
mockMvc.perform()call should targetget("/api/products/1"). - It must chain
andExpect()calls to verify the results:status().isOk()jsonPath("$.id").value(1L)jsonPath("$.name").value("Gaming Console")
- The mock setup should be
whenGetProductById_withInvalidId_thenReturnsNotFoundMethod Implementation:- The mock setup should throw an exception:
when(productService.getProductById(99L)).thenThrow(new ProductNotFoundException("Not found"));. - The
mockMvc.perform()call should targetget("/api/products/99"). - It must chain an
andExpect()call to verify the status:status().isNotFound().
- The mock setup should throw an exception: