Spis treści

REVEAL theme=simple&disableLayout=0&transition=none&controls=1&show_progress_bar=1&build_all_lists=0&show_image_borders=0&horizontal_slide_level=2&enlarge_vertical_slide_headers=0&show_slide_details=1&open_in_new_window=1&size=1024×768

<html> <style type=„text/css”> p { text-align: left;} .reveal { font-size: 30px; } .reveal section { width: 96%; margin: 0 auto; } .reveal .slides { width: 60% !important; } .reveal ul, .reveal ol { margin-left: 1.5em; } .reveal pre code {

height: 100%;
max-height: 100%;
box-sizing: border-box; }

</style> </html>

Testowanie aplikacji Spring Boot

Testy jednostkowe

Struktura testów

Struktura projektu z testami

src/
├── main/
│   └── java/com/example/app/
│       ├── controller/
│       │   └── UserController.java
│       ├── service/
│       │   └── UserService.java
│       ├── repository/
│       │   └── UserRepository.java
│       └── model/
│           └── User.java
└── test/
    └── java/com/example/app/
        ├── controller/
        │   └── UserControllerTest.java
        ├── service/
        │   └── UserServiceTest.java
        ├── repository/
        │   └── UserRepositoryTest.java
        └── integration/
            └── UserFlowIntegrationTest.java

JUnit

Adnotacja @Test oznacza metodę jako testową.


Assercje

Przykład testu jednostkowego

Przykład prostego testu jednostkowego z użyciem JUnit:

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Assertions;
 
public class CalculatorTest {
 
    @Test
    public void testAddition() {
 
        // Arrange - przygotowanie danych testowych
        Calculator calculator = new Calculator();
 
        // Act - wykonanie testowanej metody
        int result = calculator.add(2, 3);
 
        // Assert - sprawdzenie wyników
        Assertions.assertEquals(5, result);
    }
}

Parametryzowane testy

@ParameterizedTest
@ValueSource(ints = {1, 2, 3})
public void testIsPositive(int number) {
    Assertions.assertTrue(number > 0);
}

Mockito

when(mock.method()).thenReturn(value) - definiuje, co ma zwrócić mock dla danego wywołania.

verify(mock).method() - sprawdza, czy metoda została wywołana.

Adnotacje Mockito

Przykład

Test jednostkowy bez uruchamiania kontekstu Spring, z użyciem Mockito do mockowania zależności:

@ExtendWith(MockitoExtension.class)
class UserServiceTest {
 
    @Mock
    private UserRepository userRepository;
 
    @InjectMocks
    private UserService userService;
 
    @Test
    void shouldReturnUserWhenExists() {
        User user = new User(1L, "Jan");
        when(userRepository.findById(1L)).thenReturn(Optional.of(user));
 
        User result = userService.getById(1L);
 
        assertThat(result.getName()).isEqualTo("Jan");
    }
}

WebMvcTest

Test kontrolera bez uruchamiania kontekstu Spring

Test kontrolera z użyciem @WebMvcTest, który uruchamia tylko warstwę webową:

@WebMvcTest(UserController.class)
class UserControllerTest {
    @Autowired
    private MockMvc mockMvc;
 
    @MockBean
    private UserService userService;
 
    @Test
    void shouldReturnUser() throws Exception {
        when(userService.getById(1L)).thenReturn(new User(1L, "Jan"));
 
        mockMvc.perform(get("/users/1"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.name").value("Jan"));
    }
}

Test kontrolera z uruchomieniem kontekstu Spring

@SpringBootTest
@AutoConfigureMockMvc
class UserControllerTest {
    @Autowired
    private MockMvc mockMvc;
 
    @Test
    void shouldReturnUserList() throws Exception {
        mockMvc.perform(get("/users"))
            .andExpect(status().isOk())
            .andExpect(jsonPath("$[0].name").value("Jan"));
    }
}

Test bazy danych

@DataJpaTest
class UserRepositoryTest {  
    @Autowired
    private UserRepository userRepository;
 
     @Test
    void shouldFindUserByEmail() {
        User user = new User();
        user.setName("Jan");
        user.setEmail("jan@test.pl");
        userRepository.save(user);
 
        Optional<User> result = userRepository.findByEmail("jan@test.pl");
 
        assertThat(result).isPresent();
    }
}

Test integracyjny

@SpringBootTest
class UserFlowIntegrationTest {
 
    @Autowired
    private UserService userService;
 
    @Test
    void shouldCreateUser() {
        User created = userService.create("Jan", "jan@test.pl");
 
        assertThat(created.getId()).isNotNull();
    }
}

JavaDoc

Przykład komentarza JavaDoc

/**
 * Serwis odpowiedzialny za zarządzanie użytkownikami.
 */
public class UserService {
 
    /**
     * Zwraca użytkownika na podstawie identyfikatora.
     *
     * @param id identyfikator użytkownika
     * @return znaleziony użytkownik
     * @throws UserNotFoundException gdy użytkownik nie istnieje
     */
    public User getById(Long id) {
        // ...
        return null;
    }
}

Najważniejsze tagi JavaDoc

Dokumentacja