JUnit Testing in Spring Boot – A Complete Guide (Controller, Service, Repository)
Testing is one of the most important parts of building reliable applications. In Spring Boot, we usually test applications at different layers: Controller, Service, and Repository. Each layer has its own testing strategy.
In this blog, we’ll build a simple example step by step and write JUnit tests for each layer.
π Example Project – User Management
We will use a simple User entity with the following layers:
-
Controller → Handles HTTP requests
-
Service → Contains business logic
-
Repository → Interacts with the database
π’ 1. Entity & DTO
π’ 2. Repository
π’ 3. Service
π’ 4. Controller
π§ͺ Writing Tests
Now let’s write JUnit tests for each layer.
πΉ 1. Service Layer Test
Here we test the business logic in UserService.
We don’t want to hit the database → so we mock the repository using @Mock and inject it into the service with @InjectMocks.
πΉ 2. Controller Layer Test
Here we want to test the HTTP endpoints without starting the full application.
We use:
-
@WebMvcTest(UserController.class)→ Loads only Controller + MVC beans -
MockMvc→ To simulate HTTP requests -
@MockBean→ To mock the service layer inside Spring Context
πΉ 3. Repository Layer Test
Here we want to test the database interaction.
We use:
-
@DataJpaTest→ Loads only JPA-related beans with an in-memory H2 database -
Tests run against a temporary DB (no need to start the full application)
π Summary
| Layer | Annotations Used | Purpose |
|---|---|---|
| Service | @ExtendWith(MockitoExtension.class), @Mock, @InjectMocks | Test business logic with mocked dependencies |
| Controller | @WebMvcTest, @MockBean, MockMvc | Test REST endpoints without starting server |
| Repository | @DataJpaTest | Test JPA queries with in-memory DB |
✅ Conclusion
-
Service Layer → Focus on business logic, mock dependencies.
-
Controller Layer → Focus on API endpoints, mock the service.
-
Repository Layer → Focus on DB interaction using in-memory DB.
By following this layered approach, you ensure that each part of your Spring Boot application is properly tested in isolation.
No comments:
Post a Comment