Testing Spring Applications
8 min read
Welcome, intrepid coder, to the world of testing in Spring! Much like a chef tastes their soup before serving it to the entire restaurant, we must test our code to ensure it's not only functional but also robust and reliable. In this guide, we'll embark on a journey through the essential testing practices in Spring, ensuring your applications are nothing short of spectacular.
ποΈ The Testing Pyramid: Structuring Unit vs. Integration Tests in Spring
Before we dive into writing tests, let's talk strategy. Imagine you're building a grand Lego castle. You'd first want to ensure each individual Lego brick is perfectly formed (a unit test). Then, you'd check if a few bricks snap together as expected (an integration test). Finally, you'd step back and admire the entire castle to make sure it looks right and won't topple over (an end-to-end test).
This is the essence of the Testing Pyramid.
The Problem: How do we structure our tests to get the most confidence in our application with the least amount of effort and time?
The Solution: The Testing Pyramid suggests a hierarchy for our tests:
- Unit Tests (The Base): These form the foundation of your testing strategy. They are small, fast, and focus on testing a single, isolated piece of code, like a method within a class. Think of them as checking if each individual Lego brick is flawless. Because they are fast and numerous, they provide quick feedback during development.
- Integration Tests (The Middle): These tests verify that different parts of your application work together correctly. For example, does your service layer correctly interact with your data access layer? These are slower than unit tests because they often involve more components, like a database or other services.
- End-to-End (E2E) Tests (The Peak): These tests simulate a real user's journey through your application. They are the most complex and slowest to run but provide the highest level of confidence that your application is working as expected from a user's perspective.
Why is this important? A healthy testing suite has a large base of unit tests, a smaller number of integration tests, and even fewer end-to-end tests. This structure ensures you have a fast and reliable feedback loop while still being confident in the overall functionality of your application.
π Unit Testing the Service Layer: Mocking Dependencies with Mockito
Your service layer contains the core business logic of your application. When we unit test a service, we want to focus only on the logic within that service and not its dependencies (like a repository).
The Problem: How can we test a service class in isolation when it depends on other components, like a repository that interacts with a database? We don't want to spin up a whole database just to test a single method!
The Solution: We use a technique called mocking. Imagine your service needs to ask the repository for some data. Instead of talking to the real repository, we create a "mock" repository. This mock is like a stand-in actor who knows exactly what lines to say (what data to return) when asked. This allows us to test our service's logic without any external dependencies.
Mockito is a popular and powerful mocking framework in the Java world that integrates seamlessly with Spring.
Getting Started
To start, you'll need the spring-boot-starter-test dependency in your pom.xml, which conveniently includes Mockito.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>Example: Testing a ProductService
Let's say we have a ProductService that depends on a ProductRepository.
// ProductService.java
@Service
public class ProductService {
private final ProductRepository productRepository;
public ProductService(ProductRepository productRepository) {
this.productRepository = productRepository;
}
public Optional<Product> getProductById(Long id) {
return productRepository.findById(id);
}
}Now, let's write a unit test for the getProductById method.
// ProductServiceTest.java
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.when;
import static org.assertj.core.api.Assertions.assertThat;
@ExtendWith(MockitoExtension.class)
class ProductServiceTest {
@Mock
private ProductRepository productRepository;
@InjectMocks
private ProductService productService;
@Test
void whenGetProductById_thenReturnProduct() {
// 1. Arrange: Define the behavior of the mock
Product product = new Product(1L, "Test Product");
when(productRepository.findById(1L)).thenReturn(Optional.of(product));
// 2. Act: Call the method we want to test
Optional<Product> foundProduct = productService.getProductById(1L);
// 3. Assert: Check if the result is what we expect
assertThat(foundProduct).isPresent();
assertThat(foundProduct.get().getName()).isEqualTo("Test Product");
}
}What's happening here?
@ExtendWith(MockitoExtension.class): This integrates Mockito with JUnit 5.@Mock: This annotation creates a mock implementation of theProductRepository.@InjectMocks: This creates an instance ofProductServiceand injects the mocks that are created with the@Mockannotation into it.when(...).thenReturn(...): This is the magic of Mockito! We are telling our mock repository: "when thefindByIdmethod is called with the argument1L, then you should return this specificProductobject."assertThat(...): We use a library called AssertJ for our assertions, which provides a fluent and readable way to check our results.
By using Mockito, we've successfully tested our service's logic in complete isolation! π
π Testing Web Layers (Controllers) Isolation with @WebMvcTest and MockMvc
Now, let's move up the pyramid to the web layer. When we test our controllers, we want to check if they handle incoming HTTP requests correctly, call the right services, and return the expected responses.
The Problem: How do we test a controller without starting a full-blown web server and making actual HTTP requests? That would be slow and cumbersome for a simple controller test.
The Solution: Spring Boot provides the @WebMvcTest annotation. This annotation slices our application context and only loads the beans necessary for the web layer (like controllers and some web-related configurations). It doesn't load the entire application context, making it much faster than a full integration test.
To simulate HTTP requests and assert the responses, we use MockMvc.
Example: Testing a ProductController
Imagine a ProductController that uses our ProductService.
// ProductController.java
@RestController
@RequestMapping("/products")
public class ProductController {
private final ProductService productService;
public ProductController(ProductService productService) {
this.productService = productService;
}
@GetMapping("/{id}")
public ResponseEntity<Product> getProductById(@PathVariable Long id) {
return productService.getProductById(id)
.map(ResponseEntity::ok)
.orElse(ResponseEntity.notFound().build());
}
}Here's how we can test it using @WebMvcTest and MockMvc:
// ProductControllerTest.java
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.boot.test.mock.mockito.MockBean;
import org.springframework.test.web.servlet.MockMvc;
import static org.mockito.BDDMockito.given;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
@WebMvcTest(ProductController.class)
class ProductControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private ProductService productService;
@Test
void whenGetProductById_thenReturnProduct() throws Exception {
// Arrange
Product product = new Product(1L, "Test Product");
given(productService.getProductById(1L)).willReturn(Optional.of(product));
// Act & Assert
mockMvc.perform(get("/products/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").value("Test Product"));
}
}Let's break it down:
@WebMvcTest(ProductController.class): We tell Spring to only configure theProductController.@Autowired private MockMvc mockMvc;: Spring automatically configures and injects aMockMvcinstance for us.@MockBean: Since@WebMvcTestdoesn't load our service beans, we need to provide a mock implementation ofProductService.@MockBeanadds a Mockito mock to the Spring application context.mockMvc.perform(...): This is how we send a "mock" HTTP request. Here, we're performing a GET request to/products/1..andExpect(...): After performing the request, we can chain expectations to assert the response. We're checking for a 200 OK status and that the JSON response has anamefield with the value "Test Product".
Pretty neat, right? We've tested our controller's behavior without the overhead of a real server.
πΎ Integration Testing the Data Layer with @DataJpaTest and Testcontainers
Finally, let's get to the bottom of our application: the data layer. When we test our repositories, we want to ensure that our JPA mappings are correct and our queries work as expected against a real database.
The Problem: Using an in-memory database like H2 for testing can be convenient, but it might not behave exactly like our production database (e.g., PostgreSQL, MySQL). This can lead to tests that pass but code that fails in production. This is the stuff of developer nightmares! π»
The Solution: Enter Testcontainers. Testcontainers is a fantastic library that allows you to spin up a real database (or any other dependency) in a Docker container for your tests. This ensures your tests run against the same database technology you use in production.
For testing our JPA repositories, we can combine Testcontainers with Spring Boot's @DataJpaTest annotation. @DataJpaTest focuses only on JPA components and, by default, uses an embedded in-memory database. We'll configure it to use our Testcontainer instead.
Getting Started
You'll need to add the Testcontainers dependency for your specific database to your pom.xml.
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>postgresql</artifactId>
<scope>test</scope>
</dependency>Example: Testing a ProductRepository
Let's assume we have a simple ProductRepository.
// ProductRepository.java
public interface ProductRepository extends JpaRepository<Product, Long> {
}Here's how to write an integration test for it using @DataJpaTest and Testcontainers:
// ProductRepositoryTest.java
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.testcontainers.containers.PostgreSQLContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import static org.assertj.core.api.Assertions.assertThat;
@Testcontainers
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
class ProductRepositoryTest {
@Container
static PostgreSQLContainer<?> postgreSQLContainer = new PostgreSQLContainer<>("postgres:13-alpine");
@Autowired
private ProductRepository productRepository;
@Test
void whenSaveAndFindById_thenProductIsFound() {
// Arrange
Product product = new Product(null, "Test Product");
Product savedProduct = productRepository.save(product);
// Act
Optional<Product> foundProduct = productRepository.findById(savedProduct.getId());
// Assert
assertThat(foundProduct).isPresent();
assertThat(foundProduct.get().getName()).isEqualTo("Test Product");
}
}Unpacking the magic:
@Testcontainers: This JUnit 5 extension manages the lifecycle of our containers.@DataJpaTest: Configures a test slice with only JPA-related components.@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE): This is crucial! It tells Spring Boot not to replace our configured data source with an in-memory one.@Container static PostgreSQLContainer<?> ...: This declares a PostgreSQL container that will be started before our tests run and stopped afterward.- Spring Boot, with a little help from the Testcontainers library, will automatically configure the
DataSourceto connect to this temporary database.
Now, you can be confident that your repository logic works exactly as it would in production! π
π Further Reading and References
- Official Spring Boot Testing Documentation: https://docs.spring.io/spring-boot/docs/current/reference/html/features.html#features.testing
- Baeldung - Testing in Spring Boot: https://www.baeldung.com/spring-boot-testing
- Testcontainers Documentation: https://www.testcontainers.org/
- Mockito Documentation: https://site.mockito.org/
Challenge
Challenge: Write a Web Layer Test for a Book Controller
You are tasked with writing a complete JUnit 5 test class for a BookController. This controller exposes an endpoint to retrieve a book by its ID. Your test must isolate the web layer and mock the service dependency to verify the controller's behavior under different scenarios.
Given Classes (for context):
Book.java
public class Book {
private Long id;
private String title;
private String author;
// getters and setters...
}BookNotFoundException.java
@ResponseStatus(HttpStatus.NOT_FOUND)
public class BookNotFoundException extends RuntimeException {
public BookNotFoundException(String message) {
super(message);
}
}BookService.java
public interface BookService {
Book getBookById(Long id);
}BookController.java
@RestController
@RequestMapping("/api/books")
public class BookController {
private final BookService bookService;
public BookController(BookService bookService) {
this.bookService = bookService;
}
@GetMapping("/{id}")
public ResponseEntity<Book> getBookById(@PathVariable Long id) {
return ResponseEntity.ok(bookService.getBookById(id));
}
}Your Task:
Complete the BookControllerTest class to test the getBookById endpoint. You must implement two test cases:
testGetBookById_WhenBookExists_ReturnsOkAndBookJson:- Configure the mocked
BookServiceto return aBookobject whengetBookByIdis called with the ID1L. - Perform a GET request to
/api/books/1. - Assert that the HTTP response status is
200 OK. - Assert that the returned JSON body has an
idof1and atitleof"1984".
- Configure the mocked
testGetBookById_WhenBookDoesNotExist_ReturnsNotFound:- Configure the mocked
BookServiceto throw aBookNotFoundExceptionwhengetBookByIdis called with the ID99L. - Perform a GET request to
/api/books/99. - Assert that the HTTP response status is
404 Not Found.
- Configure the mocked
Expected result
The completed Java test class should contain two fully implemented test methods using @Test. The first test should mock a successful service call and assert both the HTTP status and the content of the JSON response. The second test should mock a service call that throws an exception and assert the resulting HTTP status.
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.boot.test.mock.mockito.MockBean;
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.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
// Assume the context classes (Book, BookService, etc.) are available.
@WebMvcTest(BookController.class)
public class BookControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private BookService bookService;
@Test
public void testGetBookById_WhenBookExists_ReturnsOkAndBookJson() throws Exception {
// Given
Book book = new Book();
book.setId(1L);
book.setTitle("1984");
book.setAuthor("George Orwell");
when(bookService.getBookById(1L)).thenReturn(book);
// When & Then
mockMvc.perform(get("/api/books/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id").value(1))
.andExpect(jsonPath("$.title").value("1984"));
}
@Test
public void testGetBookById_WhenBookDoesNotExist_ReturnsNotFound() throws Exception {
// Given
when(bookService.getBookById(99L)).thenThrow(new BookNotFoundException("Book not found"));
// When & Then
mockMvc.perform(get("/api/books/99"))
.andExpect(status().isNotFound());
}
}