0Pricing
Spring Boot 4 Microservices & REST APIs · Ders

JUnit ve Mockito ile Birim Testleri

Bileşenleri yalıtılmış olarak test edin.

JUnit ve Mockito ile Birim Testleri, CoddyKit'te ücretsiz bir Spring Boot 4 Microservices & REST APIs 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 Microservices & REST APIs öğrenme yolunun bir parçasıdır ve ilerlemeniz web ve CoddyKit uygulaması arasında senkronize olur. Spring Boot 4 Microservices & REST APIs kursu toplamda 4 dersten oluşur.

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

Why Unit Tests

A unit test verifies a single class in isolation, with its collaborators replaced by fakes.

  • Fast — no Spring context, no database
  • Focused — tests one piece of logic
  • Reliable — no external dependencies

JUnit 5 Basics

Spring Boot uses JUnit 5 (Jupiter). A test is a method annotated with @Test.

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

class CalculatorTest {
    @Test
    void addsTwoNumbers() {
        assertEquals(5, 2 + 3);
    }
}

Lifecycle Annotations

Use @BeforeEach to set up state before each test and @AfterEach to clean up.

@BeforeEach
void setUp() {
    calculator = new Calculator();
}

@Test
void addsCorrectly() {
    assertEquals(7, calculator.add(3, 4));
}

AssertJ Fluent Assertions

Spring Boot bundles AssertJ for readable assertions with assertThat.

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

assertThat(result).isEqualTo(42);
assertThat(list).hasSize(3).contains("a");

What is Mockito

Mockito creates mock objects — fake implementations of dependencies whose behavior you control.

This lets you test a class without its real collaborators (database, HTTP clients, etc.).

Creating Mocks

Annotate the test class with @ExtendWith(MockitoExtension.class). Use @Mock for dependencies and @InjectMocks for the class under test.

@ExtendWith(MockitoExtension.class)
class UserServiceTest {
    @Mock
    UserRepository repository;

    @InjectMocks
    UserService service;
}

Stubbing with when/thenReturn

Define a mock's behavior with when(...).thenReturn(...).

@Test
void returnsUserById() {
    User alice = new User("1", "Alice");
    when(repository.findById("1"))
        .thenReturn(Optional.of(alice));

    User result = service.getById("1");

    assertThat(result.getName()).isEqualTo("Alice");
}

Throwing from a Mock

Use thenThrow to simulate error conditions.

when(repository.findById("99"))
    .thenThrow(new RuntimeException("DB down"));

assertThrows(RuntimeException.class,
    () -> service.getById("99"));

Verifying Interactions

verify checks that a mock method was called with expected arguments.

@Test
void savesUser() {
    service.create(new User("2", "Bob"));

    verify(repository).save(any(User.class));
    verify(repository, times(1)).save(any());
}

Argument Matchers

Matchers like any(), eq(), and anyString() make stubs flexible.

when(repository.findByName(anyString()))
    .thenReturn(List.of(new User("1", "Alice")));

verify(repository).deleteById(eq("1"));

Capturing Arguments

ArgumentCaptor captures the value passed to a mock so you can assert on it.

ArgumentCaptor<User> captor =
    ArgumentCaptor.forClass(User.class);
verify(repository).save(captor.capture());
assertThat(captor.getValue().getName())
    .isEqualTo("Bob");

Quick Check

Test your understanding of Mockito.

Recap

You learned to write fast unit tests:

  • JUnit 5 with @Test, @BeforeEach
  • AssertJ assertThat for readable checks
  • Mockito @Mock / @InjectMocks
  • when/thenReturn to stub, verify to confirm calls

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 Microservices & REST APIs kursunun geri kalanını açmak için CoddyKit PRO'ya yükselt. Spring Boot 4 Microservices & REST APIs kursu toplamda 4 dersten oluşur.

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

Bileşenleri yalıtılmış olarak test edin. Spring Boot 4 Microservices & REST APIs 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 Microservices & REST APIs öğrenmeye başlamak için deneyim gerekli mi?

Önceden deneyim gerekmez. CoddyKit'te Spring Boot 4 Microservices & REST APIs, 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 Microservices & REST APIs dersinde kod yazıp çalıştırabilir miyim?

Evet. Her Spring Boot 4 Microservices & REST APIs 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. MockMvc ile Web Katmanı Testleri
  3. @SpringBootTest ile Entegrasyon Testleri
  4. Testcontainers ile Gerçek Bağımlılıklar
← Spring Boot 4 Microservices & REST APIs Sayfasına Dön