0Pricing
Testing Mastery: JUnit, Mockito & Integration Tests · Ders

@Mock ve @InjectMocks ile Sahte Nesneleri Enjekte Etme

Test edilen sınıfa sahte bağımlılıkları bağlamak ve gereksiz kurulum kodunu azaltmak için Mockito ek açıklamalarını kullanın.

@Mock ve @InjectMocks ile Sahte Nesneleri Enjekte Etme, CoddyKit'te ücretsiz bir Testing Mastery: JUnit, Mockito & Integration Tests dersidir. Bu, 4 dersinin 4. 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, Testing Mastery: JUnit, Mockito & Integration Tests öğrenme yolunun bir parçasıdır ve ilerlemeniz web ve CoddyKit uygulaması arasında senkronize olur. Testing Mastery: JUnit, Mockito & Integration Tests kursu toplamda 4 dersten oluşur.

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

Why Annotations?

Creating mocks manually with mock(Type.class) works, but for classes with several dependencies it becomes repetitive. Mockito offers annotations that declare and wire mocks for you.

  • @Mock declares a mock field
  • @InjectMocks builds the real object and injects the mocks

The Class Under Test

Imagine an OrderService that depends on a PaymentGateway. We want to test the service while controlling the gateway.

class OrderService {
  private final PaymentGateway gateway;
  OrderService(PaymentGateway gateway) { this.gateway = gateway; }
  boolean checkout(double amount) {
    return gateway.charge(amount);
  }
}

Declaring a @Mock

Annotate a field with @Mock and Mockito creates a mock instance for it automatically once the annotations are processed.

@Mock
PaymentGateway gateway;

Using @InjectMocks

@InjectMocks tells Mockito to instantiate the target and inject any @Mock fields into it, via constructor, setter, or field injection.

@Mock PaymentGateway gateway;

@InjectMocks OrderService service;

Activating the Annotations

Annotations do nothing on their own. With JUnit 5 you enable them using @ExtendWith(MockitoExtension.class) on the test class.

@ExtendWith(MockitoExtension.class)
class OrderServiceTest {
  @Mock PaymentGateway gateway;
  @InjectMocks OrderService service;
}

The Older openMocks Approach

Without the extension you can call MockitoAnnotations.openMocks(this) in a @BeforeEach method. Prefer the extension when you can.

@BeforeEach
void setUp() {
  MockitoAnnotations.openMocks(this);
}

Writing the Test

Now stub the injected mock and exercise the service. The service already holds the mocked gateway, so no manual wiring is needed.

@Test
void checkoutSucceeds() {
  when(gateway.charge(100.0)).thenReturn(true);
  assertTrue(service.checkout(100.0));
}

Injection Strategies

Mockito tries injection in this order:

  • Constructor injection (preferred)
  • Setter injection
  • Field injection

Constructor injection is the safest because it works with final fields.

Multiple Dependencies

A class with several collaborators just gets several @Mock fields. Mockito matches each by type during injection.

@Mock PaymentGateway gateway;
@Mock InventoryRepo inventory;
@InjectMocks OrderService service;

When Injection Fails Silently

If a dependency cannot be matched, the field stays null rather than throwing. A NullPointerException at test time often means injection did not happen as expected. Verify types and constructor signatures.

Cleaner Tests

Annotations remove repetitive mock(...) and new Service(...) calls, keeping each test focused on behavior instead of wiring.

Quick Check

Which annotation builds the real object and injects mocks into it?

Recap

You learned to wire mocks declaratively:

  • @Mock declares a mock field
  • @InjectMocks builds the target and injects mocks
  • Enable with @ExtendWith(MockitoExtension.class)
  • Constructor injection is preferred and supports final fields

Sıkça Sorulan Sorular

“@Mock ve @InjectMocks ile Sahte Nesneleri Enjekte Etme” dersi ücretsiz mi?

Evet — “@Mock ve @InjectMocks ile Sahte Nesneleri Enjekte Etme” 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 Testing Mastery: JUnit, Mockito & Integration Tests kursunun geri kalanını açmak için CoddyKit PRO'ya yükselt. Testing Mastery: JUnit, Mockito & Integration Tests kursu toplamda 4 dersten oluşur.

“@Mock ve @InjectMocks ile Sahte Nesneleri Enjekte Etme” dersinde ne öğreneceğim?

Test edilen sınıfa sahte bağımlılıkları bağlamak ve gereksiz kurulum kodunu azaltmak için Mockito ek açıklamalarını kullanın. Testing Mastery: JUnit, Mockito & Integration Tests 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.

Testing Mastery: JUnit, Mockito & Integration Tests öğrenmeye başlamak için deneyim gerekli mi?

Önceden deneyim gerekmez. CoddyKit'te Testing Mastery: JUnit, Mockito & Integration Tests, 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 4. dersidir.

“@Mock ve @InjectMocks ile Sahte Nesneleri Enjekte Etme” 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 Testing Mastery: JUnit, Mockito & Integration Tests dersinde kod yazıp çalıştırabilir miyim?

Evet. Her Testing Mastery: JUnit, Mockito & Integration Tests 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. Sahte Nesneler, Taslaklar ve Taklitler
  2. Mockito ile Sahte Nesneler Oluşturma
  3. Sahte Nesne Etkileşimlerini Doğrulama
  4. @Mock ve @InjectMocks ile Sahte Nesneleri Enjekte Etme
← Testing Mastery: JUnit, Mockito & Integration Tests Sayfasına Dön