Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lernen Writing Unit Tests for Spring Services | Unit Testing and Mocking in Spring Boot
Spring Testing Concepts

bookWriting 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 @MockBean annotation creates a mock of UserRepository;
  • The @Autowired annotation injects the real UserService instance, which uses the mocked repository;
  • The Mockito.when(...).thenReturn(...) method sets up the mock behavior;
  • The Assertions.assertNotNull and Assertions.assertEquals methods 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.

question mark

Which annotation is commonly used to create a mock version of a dependency when writing unit tests for Spring services?

Select the correct answer

War alles klar?

Wie können wir es verbessern?

Danke für Ihr Feedback!

Abschnitt 2. Kapitel 1

Fragen Sie AI

expand

Fragen Sie AI

ChatGPT

Fragen Sie alles oder probieren Sie eine der vorgeschlagenen Fragen, um unser Gespräch zu beginnen

bookWriting Unit Tests for Spring Services

Swipe um das Menü anzuzeigen

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 @MockBean annotation creates a mock of UserRepository;
  • The @Autowired annotation injects the real UserService instance, which uses the mocked repository;
  • The Mockito.when(...).thenReturn(...) method sets up the mock behavior;
  • The Assertions.assertNotNull and Assertions.assertEquals methods 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.

question mark

Which annotation is commonly used to create a mock version of a dependency when writing unit tests for Spring services?

Select the correct answer

War alles klar?

Wie können wir es verbessern?

Danke für Ihr Feedback!

Abschnitt 2. Kapitel 1
some-alt