0Pricing
Spring Boot 4 Complete Guide · Ders

JUnit ve Mockito ile Birim Testleri

JUnit 5 ve bağımlılıkları taklit etmek için Mockito kullanarak hizmet katmanı bileşenleriniz için etkili birim testleri yazın.

JUnit ve Mockito ile Birim Testleri, CoddyKit'te ücretsiz bir Spring Boot 4 Complete Guide dersidir. Bu, 4 dersinin 1. 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.

Welcome to Unit Testing!

In this lesson, you'll learn to write effective unit tests for your Spring Boot applications, specifically focusing on the service layer.

Unit tests are crucial for ensuring your code works as expected and catching bugs early in development. We'll use JUnit 5 and Mockito.

What is Unit Testing?

Unit testing means testing the smallest possible piece of code, called a 'unit', in isolation. For Java, a unit is typically a single method or class.

  • Isolation: Tests run independently, without external dependencies.
  • Speed: They execute very quickly, allowing frequent runs.
  • Early Detection: Catch bugs before they grow into bigger problems.

Introducing JUnit 5

JUnit 5 is the most popular testing framework for Java. It provides annotations and assertions to help you write structured and readable tests.

Let's see a basic test class structure. Notice the @Test annotation marks a method as a test case.

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;

class SimpleCalculator {
  int add(int a, int b) {
    return a + b;
  }
}

// This is a JUnit 5 test class
class SimpleCalculatorTest {

  @Test
  void testAddition() {
    SimpleCalculator calc = new SimpleCalculator();
    int result = calc.add(2, 3);
    // An 'assertion' checks if the result is correct
    assertEquals(5, result, "2 + 3 should be 5");
    System.out.println("Addition test passed!");
  }

  public static void main(String[] args) {
    // In a real project, JUnit runs tests automatically.
    // Here, we simulate a call for demonstration.
    System.out.println("--- Simulating JUnit Test ---");
    new SimpleCalculatorTest().testAddition();
    System.out.println("--- Simulation Complete ---");
  }
}

Focusing on the Service Layer

In Spring Boot, the service layer usually contains your application's business logic. It orchestrates operations, often depending on data repositories.

Unit testing services is ideal because they:

  • Hold core logic.
  • Are typically plain Java classes.
  • Can be easily isolated from external systems (like databases).

The Challenge: Dependencies

Services often depend on other components, like a UserRepository to fetch user data. If we unit test a service, we don't want to hit a real database.

This is where mocking comes in! We need to simulate these dependencies to ensure our test is truly 'unit' (isolated).

Introducing Mockito for Mocking

Mockito is a popular mocking framework for Java. It lets you create 'mock' objects that simulate the behavior of real objects.

Instead of a real UserRepository talking to a database, we'll tell a Mockito-created mock repository exactly what to return when certain methods are called.

Setting Up Mocks with Annotations

Mockito provides handy annotations to simplify creating and injecting mocks:

  • @Mock: Creates a mock object for the specified type.
  • @InjectMocks: Creates an instance of the class under test and injects the @Mock objects into it.
import org.mockito.Mock;
import org.mockito.InjectMocks;
import org.mockito.MockitoAnnotations;

// Simple dependent class (e.g., a repository)
class DataRepository {
  String findDataById(String id) {
    throw new UnsupportedOperationException("Not implemented for real use!");
  }
}

// Our service class under test
class MyService {
  private final DataRepository repository;

  MyService(DataRepository repository) {
    this.repository = repository;
  }

  String processData(String id) {
    return "Processed: " + repository.findDataById(id);
  }
}

class MyServiceTestSetup {

  @Mock
  DataRepository mockRepository; // Mock of DataRepository

  @InjectMocks
  MyService myService; // Service where mocks are injected

  MyServiceTestSetup() {
    // This initializes the mocks
    MockitoAnnotations.openMocks(this);
    System.out.println("Mocks initialized for MyServiceTest!");
    System.out.println("mockRepository is a Mockito mock: " + (mockRepository != null));
    System.out.println("myService has mock injected: " + (myService != null));
  }

  public static void main(String[] args) {
    System.out.println("--- Setting Up Mocks Demo ---");
    new MyServiceTestSetup();
    System.out.println("--- Demo Complete ---");
  }
}

Defining Mock Behavior: when().thenReturn()

Once you have a mock, you need to tell it how to behave. Use Mockito.when().thenReturn() to define what a mock method should return for specific inputs.

This allows your service to run its logic using the fake data provided by the mock, without needing a real database or external service.

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.mockito.Mock;
import org.mockito.InjectMocks;
import org.mockito.MockitoAnnotations;
import static org.mockito.Mockito.when;

// Re-using classes from previous example
class DataRepository {
  String findDataById(String id) {
    return "Real Data for " + id;
  }
}

class MyService {
  private final DataRepository repository;
  MyService(DataRepository repository) {
    this.repository = repository;
  }
  String processData(String id) {
    return "Processed: " + repository.findDataById(id);
  }
}

class MyServiceTestBehavior {

  @Mock
  DataRepository mockRepository;

  @InjectMocks
  MyService myService;

  MyServiceTestBehavior() {
    MockitoAnnotations.openMocks(this);
  }

  @Test
  void testProcessDataWithMock() {
    // 1. Define mock behavior: when findDataById("123") is called,
    //    return "Mocked Data".
    when(mockRepository.findDataById("123")).thenReturn("Mocked Data");

    // 2. Call the service method
    String result = myService.processData("123");

    // 3. Assert the result
    assertEquals("Processed: Mocked Data", result);
    System.out.println("Test passed! Result: " + result);
  }

  public static void main(String[] args) {
    System.out.println("--- Mock Behavior Demo ---");
    MyServiceTestBehavior test = new MyServiceTestBehavior();
    test.testProcessDataWithMock();
    System.out.println("--- Demo Complete ---");
  }
}

Verifying Interactions with verify()

Sometimes, you don't just care about the return value, but also whether a specific method on a mock was called, and with what arguments.

Mockito's verify() method lets you assert that interactions with your mocks happened as expected. This is great for checking side effects.

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.mockito.Mock;
import org.mockito.InjectMocks;
import org.mockito.MockitoAnnotations;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.times;

// Re-using classes from previous example
class DataRepository {
  String findDataById(String id) {
    return "Real Data for " + id;
  }
}

class MyService {
  private final DataRepository repository;
  MyService(DataRepository repository) {
    this.repository = repository;
  }
  String processData(String id) {
    return "Processed: " + repository.findDataById(id);
  }
  void saveData(String id, String data) {
    // Imagine this saves to DB via repository
    repository.findDataById(id); // Example interaction
    System.out.println("Saving data via mock...");
  }
}

class MyServiceTestVerification {

  @Mock
  DataRepository mockRepository;

  @InjectMocks
  MyService myService;

  MyServiceTestVerification() {
    MockitoAnnotations.openMocks(this);
  }

  @Test
  void testProcessDataAndVerify() {
    // Define mock behavior
    when(mockRepository.findDataById("456")).thenReturn("Verify Data");

    // Call the service method
    String result = myService.processData("456");

    // Assert the result
    assertEquals("Processed: Verify Data", result);

    // Verify that findDataById was called exactly once with "456"
    verify(mockRepository, times(1)).findDataById("456");
    System.out.println("Test passed! Method interaction verified.");
  }

  public static void main(String[] args) {
    System.out.println("--- Mock Verification Demo ---");
    MyServiceTestVerification test = new MyServiceTestVerification();
    test.testProcessDataAndVerify();
    System.out.println("--- Demo Complete ---");
  }
}

Quick Check: Mockito's Role

When unit testing a Spring service that depends on a repository, what is the primary role of Mockito?

Recap: Unit Testing Mastery

Congratulations! You've taken your first steps into effective unit testing with Spring Boot.

  • Unit tests verify small code units in isolation.
  • JUnit 5 is our testing framework, using @Test.
  • We focus on the service layer for business logic.
  • Mockito helps us create mock objects for dependencies.
  • Use @Mock, @InjectMocks to set up tests.
  • Define mock behavior with when().thenReturn().
  • Verify interactions with verify().

Keep practicing, and your code will be more robust than ever!

Sıkça Sorulan Sorular

“JUnit ve Mockito ile Birim Testleri” dersi ücretsiz mi?

Evet — “JUnit ve Mockito ile Birim Testleri” 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.

“JUnit ve Mockito ile Birim Testleri” dersinde ne öğreneceğim?

JUnit 5 ve bağımlılıkları taklit etmek için Mockito kullanarak hizmet katmanı bileşenleriniz için etkili birim testleri yazı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 1. dersidir.

“JUnit ve Mockito ile Birim Testleri” 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