0Pricing
Spring Boot 4 Complete Guide · Ders

Katman Testleri ve TestContainers

Belirli katmanlar için katman testlerinden (`@WebMvcTest`, `@DataJpaTest`) yararlanın ve harici hizmetler için Testcontainers ile entegrasyon sağlayın.

Katman Testleri ve TestContainers, CoddyKit'te ücretsiz bir Spring Boot 4 Complete Guide dersidir. Bu, 4 dersinin 3. dersidir. Aşağıdan dersin tamamını ücretsiz okuyabilir, sonra tarayıcıda yerleşik kod editörü ve 7/24 yapay zeka koçu ile uygulamalı olarak pratik yapabilirsin. Bu, Spring Boot 4 Complete Guide öğrenme yolunun bir parçasıdır ve ilerlemeniz web ve CoddyKit uygulaması arasında senkronize olur. Spring Boot 4 Complete Guide kursu toplamda 4 dersten oluşur.

Bu dersin bazı bölümleri henüz çevrilmemiş olup İngilizce olarak gösterilmektedir.

Slice Testing: Focused Tests

Welcome to Lesson 3! In previous lessons, we learned about unit and full integration tests. Now, let's explore slice tests.

Slice tests focus on testing a specific 'slice' or layer of your application, like the web layer or the data layer, in isolation. This makes them:

  • Faster: They load only necessary parts of the Spring context.
  • More targeted: You test specific component interactions without the overhead of the entire application.

Testing Web Layers with @WebMvcTest

When you want to test your Spring MVC controllers and their interactions with HTTP requests, @WebMvcTest is your go-to annotation.

It auto-configures Spring MVC components (like @Controller, @RestController, @ControllerAdvice) but excludes other parts of your application, such as services and repositories. This ensures your test focuses solely on the web layer.

It uses MockMvc to simulate HTTP requests and responses without starting a full HTTP server.

Your First @WebMvcTest

Here's an example of a simple controller and how to test it using @WebMvcTest and MockMvc. Notice how we define the controller class in the annotation.

This test simulates a GET request to /hello and asserts the HTTP status and response content. Remember, this code runs within a JUnit test environment, not as a standalone main method.

package com.coddykit.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {
    @GetMapping("/hello")
    public String sayHello() {
        return "Hello CoddyKit!";
    }
}

// --- Test Class ---
package com.coddykit;

import com.coddykit.controller.HelloController;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.web.servlet.MockMvc;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@WebMvcTest(HelloController.class)
public class HelloControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    void helloEndpointReturnsGreeting() throws Exception {
        mockMvc.perform(get("/hello"))
                .andExpect(status().isOk())
                .andExpect(content().string("Hello CoddyKit!"));
    }
}

Mocking Services in Web Tests

What if your controller depends on a service? Since @WebMvcTest doesn't load service beans, you'll need to provide a mock. This is where @MockBean comes in handy.

@MockBean replaces an existing bean in the application context with a Mockito mock. This lets you define the behavior of the service without needing its actual implementation, keeping your test isolated to the controller logic.

package com.coddykit.service;

import org.springframework.stereotype.Service;

@Service
public class GreetingService {
    public String getGreeting() {
        return "Hello from Service!";
    }
}

package com.coddykit.controller;

import com.coddykit.service.GreetingService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class GreetingController {
    private final GreetingService greetingService;

    public GreetingController(GreetingService greetingService) {
        this.greetingService = greetingService;
    }

    @GetMapping("/greeting")
    public String getCustomGreeting() {
        return greetingService.getGreeting();
    }
}

// --- Test Class ---
package com.coddykit;

import com.coddykit.controller.GreetingController;
import com.coddykit.service.GreetingService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.web.servlet.MockMvc;

import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@WebMvcTest(GreetingController.class)
public class GreetingControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private GreetingService greetingService;

    @Test
    void greetingEndpointReturnsMockedGreeting() throws Exception {
        when(greetingService.getGreeting()).thenReturn("Mocked Greeting!");

        mockMvc.perform(get("/greeting"))
                .andExpect(status().isOk())
                .andExpect(content().string("Mocked Greeting!"));
    }
}

Testing Data Layers with @DataJpaTest

Moving to the data layer, @DataJpaTest is designed for testing JPA repositories. It's ideal for verifying that your entities are correctly mapped and your repository methods work as expected.

This annotation:

  • Configures an in-memory embedded database (like H2) by default.
  • Scans for @Entity classes and Spring Data JPA repositories.
  • Provides a TestEntityManager for interacting with the database directly in tests.

Your First @DataJpaTest

Let's create a simple Product entity and its repository, then write a @DataJpaTest to ensure data can be saved and retrieved. The TestEntityManager helps set up test data.

Each @DataJpaTest runs in a transaction and rolls back at the end, ensuring a clean state for every test.

package com.coddykit.entity;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;

@Entity
public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private double price;

    public Product() {}
    public Product(String name, double price) {
        this.name = name;
        this.price = price;
    }

    public Long getId() { return id; }
    public void setId(Long id) { this.id = id; }
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public double getPrice() { return price; }
    public void setPrice(double price) { this.price = price; }
}

package com.coddykit.repository;

import com.coddykit.entity.Product;
import org.springframework.data.jpa.repository.JpaRepository;

public interface ProductRepository extends JpaRepository<Product, Long> {
    Product findByName(String name);
}

// --- Test Class ---
package com.coddykit;

import com.coddykit.entity.Product;
import com.coddykit.repository.ProductRepository;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;

import static org.assertj.core.api.Assertions.assertThat;

@DataJpaTest
public class ProductRepositoryTest {

    @Autowired
    private TestEntityManager entityManager;

    @Autowired
    private ProductRepository productRepository;

    @Test
    void productCanBeSavedAndFound() {
        Product newProduct = new Product("Laptop", 1200.00);
        entityManager.persist(newProduct);
        entityManager.flush();

        Product foundProduct = productRepository.findByName("Laptop");

        assertThat(foundProduct).isNotNull();
        assertThat(foundProduct.getName()).isEqualTo("Laptop");
        assertThat(foundProduct.getPrice()).isEqualTo(1200.00);
    }
}

Testcontainers: Real External Services

While in-memory databases are great for speed, they don't always mimic production environments perfectly. This is where Testcontainers shine!

Testcontainers is a Java library that provides lightweight, throwaway instances of databases, message brokers, web browsers, or anything else that can run in a Docker container. You get a real service for your tests, ensuring higher fidelity to your production setup.

  • No more mock databases that behave differently.
  • Consistent test environments across machines.
  • Supports a wide range of services.

Setting Up Your First Container

To use Testcontainers, you need Docker running on your machine. Here's a basic example of how you might start a Redis container within a JUnit test using GenericContainer. This demonstrates the lifecycle of a container for testing.

In a real test, you'd integrate a client (e.g., Spring Data Redis) to interact with this running Redis instance.

package com.coddykit;

import org.junit.jupiter.api.Test;
import org.testcontainers.containers.GenericContainer;
import org.testcontainers.utility.DockerImageName;

import static org.assertj.core.api.Assertions.assertThat;

public class RedisContainerTest {

    private static GenericContainer<?> redis = new GenericContainer<>(DockerImageName.parse("redis:5.0.3-alpine"))
            .withExposedPorts(6379);

    @Test
    void redisContainerStartsAndIsAccessible() {
        redis.start();
        assertThat(redis.isRunning()).isTrue();
        System.out.println("Redis container is running on port: " + redis.getFirstMappedPort());
        redis.stop();
    }
}

DataJpaTest with Testcontainers

Combining @DataJpaTest with Testcontainers allows you to test your repositories against a real database, like PostgreSQL, instead of an in-memory one. This provides the best of both worlds: focused data layer testing with a realistic database environment.

We use @Testcontainers to enable Testcontainers integration and @Container to define our database container. @DynamicPropertySource dynamically sets Spring's datasource properties to connect to the running container.

package com.coddykit;

import com.coddykit.entity.Product;
import com.coddykit.repository.ProductRepository;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;
import org.testcontainers.containers.PostgreSQLContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;

import static org.assertj.core.api.Assertions.assertThat;

@DataJpaTest
@Testcontainers
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
public class ProductRepositoryPostgresTest {

    @Container
    static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:13");

    @DynamicPropertySource
    static void configureProperties(DynamicPropertyRegistry registry) {
        registry.add("spring.datasource.url", postgres::getJdbcUrl);
        registry.add("spring.datasource.username", postgres::getUsername);
        registry.add("spring.datasource.password", postgres::getPassword);
    }

    @Autowired
    private TestEntityManager entityManager;

    @Autowired
    private ProductRepository productRepository;

    @Test
    void productCanBeSavedAndFoundInRealDb() {
        Product newProduct = new Product("Monitor", 300.00);
        entityManager.persist(newProduct);
        entityManager.flush();

        Product foundProduct = productRepository.findByName("Monitor");

        assertThat(foundProduct).isNotNull();
        assertThat(foundProduct.getName()).isEqualTo("Monitor");
    }
}

Check Your Understanding

Time to test what you've learned about focused testing strategies.

Slice Testing & Testcontainers Recap

You've successfully explored advanced testing techniques! Here's a quick recap:

  • Slice tests (like @WebMvcTest and @DataJpaTest) allow you to test specific layers of your application in isolation, making tests faster and more focused.
  • @WebMvcTest is for the web layer, using MockMvc to simulate requests.
  • @DataJpaTest is for the data layer, often with an in-memory database.
  • Testcontainers provide a powerful way to use real external services (like PostgreSQL or Redis) in Docker containers for your tests, ensuring high fidelity to production environments.

These tools are invaluable for building robust and reliable Spring Boot applications!

Sıkça Sorulan Sorular

“Katman Testleri ve TestContainers” dersi ücretsiz mi?

Evet — “Katman Testleri ve TestContainers” dersin tüm metni burada web'de ücretsiz olarak okunabilir. Etkileşimli olarak pratik yapmak (yerleşik kod editörü ve 7/24 yapay zeka koçu) ve Spring Boot 4 Complete Guide kursunun geri kalanını açmak için CoddyKit PRO'ya yükselt. Spring Boot 4 Complete Guide kursu toplamda 4 dersten oluşur.

“Katman Testleri ve TestContainers” dersinde ne öğreneceğim?

Belirli katmanlar için katman testlerinden (`@WebMvcTest`, `@DataJpaTest`) yararlanın ve harici hizmetler için Testcontainers ile entegrasyon sağlayın. Spring Boot 4 Complete Guide ile uygulamalı kodu tarayıcıda doğrudan çalıştırarak pratik yaparsın ve 7/24 yapay zeka koçu dersi çalışırken sorularını yanıtlar.

Spring Boot 4 Complete Guide öğrenmeye başlamak için deneyim gerekli mi?

Önceden deneyim gerekmez. CoddyKit'te Spring Boot 4 Complete Guide, başlangıçtan ileri seviyeye kadar yapılandırıldığı için buradan başlayabilir veya başından başlayıp kendi hızında ilerleme yapabilirsin. Bu, 4 dersinin 3. dersidir.

“Katman Testleri ve TestContainers” dersi ne kadar sürer?

Çoğu CoddyKit dersi yaklaşık 5–10 dakika sürer. Her biri kısa ve etkileşimli olduğu için sabit ilerleme yaparsın ve web ile uygulama arasında tam olarak bıraktığın yerden devam edebilirsin.

Bu Spring Boot 4 Complete Guide dersinde kod yazıp çalıştırabilir miyim?

Evet. Her Spring Boot 4 Complete Guide dersi yerleşik bir kod editörü içerir, bu sayede tarayıcıda gerçek kod yazıp çalıştırabilir ve anlık yapay zeka geri bildirimi alırsın — yerel kurulum gerekli değildir.

Bu kursun tüm dersleri

  1. JUnit ve Mockito ile Birim Testleri
  2. Spring Boot ile Entegrasyon Testleri
  3. Katman Testleri ve TestContainers
  4. Web Denetleyicilerini MockMvc ile Test Etme
← Spring Boot 4 Complete Guide Sayfasına Dön