Writing Unit Tests for Spring Services
Writing Unit Tests for Spring Services
Unit tests help you verify that your Spring services work as expected. In Spring Boot, you use the @SpringBootTest and @MockBean annotations to create isolated, repeatable tests for your service classes.
Key Steps to Write Unit Tests for Services
- Identify the class or method you want to test;
- Mock dependencies, such as repositories or other services, to isolate the logic;
- Use assertions to check the output matches your expectations.
Example: Testing a Service with a Mocked Repository
Suppose you have a service class called UserService that depends on a UserRepository:
@Service
public class UserService {
private final UserRepository userRepository;
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public User findUserById(Long id) {
return userRepository.findById(id).orElse(null);
}
}
To test UserService without accessing a real database, mock the UserRepository:
@SpringBootTest
public class UserServiceTest {
@MockBean
private UserRepository userRepository;
@Autowired
private UserService userService;
@Test
public void testFindUserById_ReturnsUser() {
User mockUser = new User(1L, "Alice");
Mockito.when(userRepository.findById(1L)).thenReturn(Optional.of(mockUser));
User result = userService.findUserById(1L);
Assertions.assertNotNull(result);
Assertions.assertEquals("Alice", result.getName());
}
}
Key points in the example:
- The
@MockBeanannotation creates a mock ofUserRepository; - The
@Autowiredannotation injects the realUserServiceinstance, which uses the mocked repository; - The
Mockito.when(...).thenReturn(...)method sets up the mock behavior; - The
Assertions.assertNotNullandAssertions.assertEqualsmethods check the result.
Best Practices
- Test only the logic inside your service, not the behavior of dependencies;
- Use clear, descriptive method names for your tests;
- Keep each test focused on one scenario.
Unit testing your Spring services ensures your business logic works and gives you confidence to make future changes.
Thanks for your feedback!
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat
Awesome!
Completion rate improved to 8.33
Writing Unit Tests for Spring Services
Swipe to show menu
Writing Unit Tests for Spring Services
Unit tests help you verify that your Spring services work as expected. In Spring Boot, you use the @SpringBootTest and @MockBean annotations to create isolated, repeatable tests for your service classes.
Key Steps to Write Unit Tests for Services
- Identify the class or method you want to test;
- Mock dependencies, such as repositories or other services, to isolate the logic;
- Use assertions to check the output matches your expectations.
Example: Testing a Service with a Mocked Repository
Suppose you have a service class called UserService that depends on a UserRepository:
@Service
public class UserService {
private final UserRepository userRepository;
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public User findUserById(Long id) {
return userRepository.findById(id).orElse(null);
}
}
To test UserService without accessing a real database, mock the UserRepository:
@SpringBootTest
public class UserServiceTest {
@MockBean
private UserRepository userRepository;
@Autowired
private UserService userService;
@Test
public void testFindUserById_ReturnsUser() {
User mockUser = new User(1L, "Alice");
Mockito.when(userRepository.findById(1L)).thenReturn(Optional.of(mockUser));
User result = userService.findUserById(1L);
Assertions.assertNotNull(result);
Assertions.assertEquals("Alice", result.getName());
}
}
Key points in the example:
- The
@MockBeanannotation creates a mock ofUserRepository; - The
@Autowiredannotation injects the realUserServiceinstance, which uses the mocked repository; - The
Mockito.when(...).thenReturn(...)method sets up the mock behavior; - The
Assertions.assertNotNullandAssertions.assertEqualsmethods check the result.
Best Practices
- Test only the logic inside your service, not the behavior of dependencies;
- Use clear, descriptive method names for your tests;
- Keep each test focused on one scenario.
Unit testing your Spring services ensures your business logic works and gives you confidence to make future changes.
Thanks for your feedback!