Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Writing Unit Tests for Spring Services | Unit Testing and Mocking in Spring Boot
Practice
Projects
Quizzes & Challenges
Quizzes
Challenges
/
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

Var alt klart?

Hvordan kan vi forbedre det?

Tak for dine kommentarer!

Sektion 2. Kapitel 1

Spørg AI

expand

Spørg AI

ChatGPT

Spørg om hvad som helst eller prøv et af de foreslåede spørgsmål for at starte vores chat

bookWriting Unit Tests for Spring Services

Stryg for at vise menuen

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

Var alt klart?

Hvordan kan vi forbedre det?

Tak for dine kommentarer!

Sektion 2. Kapitel 1
some-alt