Przejdź do treści
Biblioteka skilli
Programowanie · Testowanie

testing-pyramid

/testing-pyramid

Pomaga pisać testy jednostkowe, slice i integracyjne w Javie, z Mockito, @WebMvcTest, @DataJpaTest oraz Testcontainers.

Licencja
MIT
Ostatnia zmiana repozytorium
22.10.2026

Ocena i bezpieczeństwo

100/ 100Klasa: dobry
Format25 / 25
Frontmatter z nazwą i opisem, poprawna nazwa, opis do 1024 znaków, nazwa zgodna z folderem.
Odkrywalność25 / 25
Opis mówi, kiedy użyć skilla, ma sensowną długość i jest w 3. osobie.
Treść35 / 35
Co najmniej 150 słów i do 500 linii, nagłówki, listy kroków, przykłady albo kod.
Higiena15 / 15
Bez zaślepek typu TODO, bez ścieżek Windows, z licencją.
Ryzykobrak sygnałów w skanie
Pliki w paczce
4
Skrypty
2
Komentarze HTML
1
Adresy URL w SKILL.md
0
Przestarzałość

Brak sygnałów. Repozytorium zmienione 22.10.2026, bez odwołań do wycofanych modeli i API.

Licencja

MIT, otwarta: można używać i zmieniać, z zachowaniem informacji o autorze.

Co sprawdzić przed instalacją
  • 2 skrypty w paczce. Przejrzyj je przed instalacją, bo Claude może je uruchomić.
  • SKILL.md zawiera komentarze HTML (1). Nie widać ich w podglądzie Markdown, a model je czyta.

Skrypty: examples/bad-controller-test.java, examples/good-controller-test.java

Co robi i kiedy

Pomaga pisać testy jednostkowe, slice i integracyjne w Javie, z Mockito, @WebMvcTest, @DataJpaTest oraz Testcontainers.

Oryginalny opis (EN)

Use when writing tests of any kind — unit, slice, or integration. Covers test structure, naming conventions, Mockito patterns, @WebMvcTest, @DataJpaTest, and Testcontainers setup.

Jak działa

  1. Structure
  2. Unit Tests — Services
  3. Slice Tests — Controllers (@WebMvcTest)
  4. Slice Tests — Repositories (@DataJpaTest)
  5. Integration Tests — Testcontainers
  6. Naming Convention
  7. Testcontainers Dependencies
  8. Gotchas
Sekcje z nagłówków SKILL.md, w oryginale · 243 linii, 704 słów
Podgląd SKILL.md
---
name: testing-pyramid
description: >
  Use when writing tests of any kind — unit, slice, or integration. Covers test structure,
  naming conventions, Mockito patterns, @WebMvcTest, @DataJpaTest, and Testcontainers setup.
---

# Testing Pyramid

## Structure

```
Unit Tests         — fast, no Spring context, mock dependencies    (70%)
Slice Tests        — partial Spring context (@WebMvcTest, @DataJpaTest) (20%)
Integration Tests  — full context + real DB via Testcontainers     (10%)
```

## Unit Tests — Services

```java
@ExtendWith(MockitoExtension.class)
class OrderServiceTest {

    @Mock private OrderRepository orderRepository;
    @Mock private InventoryService inventoryService;

    @InjectMocks private OrderService orderService;

    @Test
    void createOrder_whenItemsAvailable_shouldSaveAndReturnOrder() {
        // Given
        var request = new CreateOrderRequest("user@example.com", List.of(new OrderItemRequest(UUID.randomUUID(), 2)));
        var savedOrder = Order.create("user@example.com");
        when(orderRepository.save(any(Order.class))).thenReturn(savedOrder);
        doNothing().when(inventoryService).reserve(any());

        // When
        Order result = orderService.createOrder(request);

        // Then
        assertThat(result).isNotNull();
        assertThat(result.getCustomerEmail()).isEqualTo("user@example.com");
        verify(inventoryService).reserve(request.items());
        verify(orderRepository).save(any(Order.class));
    }

    @Test
    void createOrder_whenInventoryUnavailable_shouldThrowException() {
        // Given
        var request = new CreateOrderRequest("user@example.com", List.of());
        doThrow(new InsufficientInventoryException("Out of stock"))
            .when(inventoryService).reserve(any());

        // When / Then
        assertThatThrownBy(() -> orderService.createOrder(request))
            .isInstanceOf(InsufficientInventoryException.class)
            .hasMessage("Out of stock");
    }
}
```

## Slice Tests — Controllers (@WebMvcTest)

```java
// POSTs need .with(csrf()): @WebMvcTest applies Boot's default security (CSRF on);
// @WithMockUser only authenticates. Add @Import(SecurityConfig.class) to test your real rules.
// import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
@WebMvcTest(OrderController.class)
class OrderControllerTest {

    @Autowired MockMvc mockMvc;
    @Autowired ObjectMapper objectMapper;
    @MockitoBean OrderService orderService;

    @Test
    @WithMockUser(roles = "USER")
    void createOrder_withValidRequest_shouldReturn201() throws Exception {
        // Given
        var request = new CreateOrderRequest("user@example.com",
            List.of(new OrderItemRequest(UUID.randomUUID(), 1))); // items are @NotEmpty
        var order = Order.create("user@example.com");
        when(orderService.createOrder(any())).thenReturn(order);

        // When / Then
        mockMvc.perform(post("/api/v1/orders").with(csrf())
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(request)))
            .andExpect(status().isCreated())
            .andExpect(jsonPath("$.success").value(true))
            .andExpect(jsonPath("$.data.customerEmail").value("user@example.com"));
    }

    @Test
    @WithMockUser
    void createOrder_withInvalidRequest_shouldReturn400() throws Exception {
        mockMvc.perform(post("/api/v1/orders").with(csrf())
                .contentType(MediaType.APPLICATION_JSON)
                .content("{}")) // missing required fields
            .andExpect(status().isBadRequest())
            .andExpect(jsonPath("$.success").value(false))
            .andExpect(jsonPath("$.error.code").value("VALIDATION_FAILED"));
    }
}
```

## Slice Tests — Repositories (@DataJpaTest)

```java
@DataJpaTest
@AutoConfigureTestDatabase(replace = Replace.NONE) // use real DB (Testcontainers)
@Import(TestcontainersConfig.class)
class OrderRepositoryTest {

    @Autowired OrderRepository orderRepository;

    @Test
    void findByStatus_shouldReturnMatchingOrders() {
        // Given
        var order1 = orderRepository.save(Order.create("a@example.com"));
        var order2 = orderRepository.save(Order.create("b@example.com"));
        order2.ship(); // change status
        orderRepository.save(order2);

        // When
        List<Order> pending = orderRepository.findByStatus(OrderStatus.PENDING, Pageable.unpaged()).getContent();

        // Then
        assertThat(pending).hasSize(1);
        assertThat(pending.get(0).getCustomerEmail()).isEqualTo("a@example.com");
    }
}
```

## Integration Tests — Testcontainers

This application-level example assumes the first-party JWT setup and order API from
the related skills. Supply `src/test/resources/fixtures/order-user-and-product.sql` for
your application's schema: an enabled USER named `buyer@example.com` and an in-stock
product with ID `00000000-0000-0000-0000-000000000001`. Run it only against the disposable
test database. Adapt the fixtures and response DTO to your application.

Load the real persisted user before signing the token. `@WithMockUser` does not authenticate
a request sent over HTTP to a random-port server. For OAuth2 resource servers, use a test
issuer instead of introducing this application's JWT service.

```java
// Shared config — reuse container across tests
@TestConfiguration(proxyBeanMethods = false)
public class TestcontainersConfig {

    @Bean
    @ServiceConnection
    PostgreSQLContainer postgresContainer() { // org.testcontainers.postgresql.PostgreSQLContainer (TC 2)
        return new PostgreSQLContainer("postgres:16-alpine");
    }
}

// Full integration test
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureRestTestClient
@Import(TestcontainersConfig.class)
class OrderIntegrationTest {

    @Autowired RestTestClient restTestClient;
    @Autowired OrderRepository orderRepository;
    @Autowired JwtService jwtService;
    @Autowired UserDetailsService userDetailsService;

    private static final UUID PRODUCT_ID = UUID.fromString("00000000-0000-0000-0000-000000000001");
    private static final ParameterizedTypeReference<ApiResponse<OrderResponse>> RESPONSE_TYPE =
        new ParameterizedTypeReference<>() {};

    @Test
    @Sql("/fixtures/order-user-and-product.sql")
    void createAndRetrieveOrder_endToEnd() {
        var user = userDetailsService.loadUserByUsername("buyer@example.com");
        String token = jwtService.generateAccessToken(user);
        var createRequest = new CreateOrderRequest("buyer@example.com",
            List.of(new CreateOrderRequest.OrderItemRequest(PRODUCT_ID, 1)));
        var created = restTestClient.post()
            .uri("/api/v1/orders")
            .headers(headers -> headers.setBearerAuth(token))
            .body(createRequest)
            .exchange()
            .expectStatus().isCreated()
            .expectBody(RESPONSE_TYPE)
            .returnResult().getResponseBody();
        assertThat(created).isNotNull();
        assertThat(created.success()).isTrue();
        assertThat(created.data()).isNotNull();
        UUID id = created.data().id();
        assertThat(id).isNotNull();
        assertThat(orderRepository.findById(id)).isPresent();

        var retrieved = restTestClient.get()
            .uri("/api/v1/orders/{id}", id)
            .headers(headers -> headers.setBearerAuth(token))
            .exchange()
            .expectStatus().isOk()
            .expectBody(RESPONSE_TYPE)
            .returnResult().getResponseBody();
        assertThat(retrieved).isNotNull();
        assertThat(retrieved.success()).isTrue();
        assertThat(retrieved.data()).isNotNull();
        assertThat(retrieved.data().id()).isEqualTo(id);
        assertThat(retrieved.data().status()).isEqualTo(created.data().status());
        assertThat(retrieved.data().items()).hasSize(1);
        assertThat(retrieved.data().items().get(0).productId()).isEqualTo(PRODUCT_ID);
        assertThat(retrieved.data().items().get(0).quantity()).isEqualTo(1);
    }
}
```

## Naming Convention

```
// Method name: methodName_condition_expectedBehavior
createOrder_whenItemsAvailable_shouldSaveOrder()
findById_whenOrderNotFound_shouldThrowNotFoundException()
login_withInvalidCredentials_shouldReturn401()
```

## Testcontainers Dependencies

```xml
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-testcontainers</artifactId>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.testcontainers</groupId>
    <artifactId>testcontainers-postgresql</artifactId> <!-- Testcontainers 2 renamed every module -->
    <scope>test</scope>
</dependency>
```

## Gotchas
- Agent uses `org.testcontainers:postgresql` on Boot 4 — Testcontainers 2 (managed by Boot 4.1) publishes `testcontainers-postgresql`; the old artifact has no managed version. Import `org.testcontainers.postgresql.PostgreSQLContainer` (non-generic); the old `containers` package is deprecated
- Agent uses `@SpringBootTest` for everything — use slices for speed
- Agent uses `H2` in-memory DB for `@DataJpaTest` — use Testcontainers for accuracy
- Agent uses `@MockBean` — removed in Boot 4; use `@MockitoBean` (and `@MockitoSpyBean` for spies)
- Agent uses `TestRestTemplate` by habit — prefer `RestTestClient` with `@AutoConfigureRestTestClient` for Boot 4 HTTP integration tests
- Agent uses `Mockito.mock()` instead of `@Mock` — use annotations with `@ExtendWith(MockitoExtension.class)`
- Agent forgets `@WithMockUser` on controller tests — security filter blocks all requests with 401
- Agent POSTs in `@WebMvcTest` without `.with(csrf())` — Boot's default security enables CSRF, so every write returns 403 even with `@WithMockUser`
- Agent uses `assertEquals` from JUnit — use AssertJ (`assertThat(...).isEqualTo(...)`)
- Agent names tests `test_createOrder()` — use `createOrder_condition_expected()` pattern
Pliki w paczce (4)
  • SKILL.md 10 KB
  • agents/openai.yaml 1 KB
  • examples/bad-controller-test.java 1 KB
  • examples/good-controller-test.java 1 KB

Wersje

RepozytoriumWynikLicencja
Ta strona · rrezartprebreza/spring-boot-skills100MIT
rrezartprebreza/spring-boot-skills100MIT
fatonh/symfony-skills100MIT

Migawka bazy z 13.11.2026 · wersja paczki 9b46386906c3 (skrót SHA-256 całej paczki)

Pobrania w ostatnich 30 dniach: 0 · ranking

Zgłoś problem z tym skillem: szkodliwa treść, błędny opis albo prośba autora o usunięcie.

Podobne skille

  • 100spring-boot-testing
    Pomaga pisać testy Spring Boot 4: jednostkowe, wycinkowe, integracyjne z Testcontainers i testy architektury ArchUnit.
  • 100spring-boot-test-patterns
    Podaje wzorce testowania aplikacji Spring Boot: testy jednostkowe, integracyjne, slice i kontenerowe z JUnit 5, Mockito i Testcontainers oraz optymalizacja wydajności testów.
  • 100spring-boot-testing
    Wspiera testowanie Spring Boot 4: testy slice, integracyjne, Testcontainers z @ServiceConnection, testy bezpieczeństwa i zdarzeń Modulith, z migracją z @MockBean na @MockitoBean.
  • 100java-spring-boot-testing
    Prowadzi przez testowanie w Spring Boot: testy jednostkowe z Mockito, testy kontrolerów (MockMVC, @WebMvcTest, WebTestClient), repozytoria JPA, Testcontainers, Spring Cloud Contract i testy obciążeniowe.
  • 100testing-patterns
    Pomaga pisać testy dla aplikacji Spring Boot z JUnit 5, Mockito, MockMvc i Testcontainers, w tym przypadki negatywne.
  • 100spring-boot-test
    Wprowadza w testowanie Spring Boot: @SpringBootTest, testy slice, MockMvc, mockowanie @MockBean, konfigurację testów i narzędzia pomocnicze.

Uwagi i zgłoszenia

Wiadomość trafi do Bartosza Sokolińskiego. Adres e-mail jest potrzebny tylko do odpowiedzi. Szczegóły w polityce prywatności.