Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprenda 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

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 2. Capítulo 1

Pergunte à IA

expand

Pergunte à IA

ChatGPT

Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo

Suggested prompts:

Can you explain how to mock multiple dependencies in a service test?

What is the difference between @MockBean and @Mock in Spring tests?

Can you show how to test a service method that throws an exception?

bookWriting Unit Tests for Spring Services

Deslize para mostrar o 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 @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

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 2. Capítulo 1
some-alt