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

Mockito ile Sahte Nesneler Oluşturma

Bağımlılıklar için sahte nesneler oluşturmak ve sınanan birimi işbirlikçilerinden yalıtmak üzere Mockito'yu kullanın.

Mockito ile Sahte Nesneler Oluşturma, CoddyKit'te ücretsiz bir Testing Mastery: JUnit, Mockito & Integration Tests dersidir. Bu, 4 dersinin 2. 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.

Intro to Mockito Mocks

In the previous lesson, we learned about the concept of a mock object. Mocks are special test doubles that let us control the behavior of dependencies.

Now, we'll dive into Mockito, a popular Java mocking framework, to see how easy it is to create these powerful tools for your tests.

Why Create Mocks?

Creating mocks is crucial for effective unit testing:

  • Isolation: Mocks allow you to test a single unit of code in isolation, without worrying about its real dependencies.
  • Control: You can program mocks to behave exactly as needed for your test scenario, simulating various outcomes.
  • Speed: Mocks avoid slow operations like database calls or network requests, making your tests run much faster.

The `Mockito.mock()` Method

The simplest way to create a mock object in Mockito is by using the Mockito.mock() static method. You pass it the Class or Interface you want to mock.

It returns a new mock instance that looks and acts like the real object, but without its actual implementation logic.

Basic Mock Creation Example

Let's create a mock for a simple EmailService interface. Run the code to see how a mock object is created.

import org.mockito.Mockito;

interface EmailService {
  void sendEmail(String to, String subject, String body);
  String getServiceStatus();
}

public class Main {
  public static void main(String[] args) {
    EmailService mockEmailService = Mockito.mock(EmailService.class);
    System.out.println("Mock created: " + mockEmailService.getClass().getName());
  }
}

Understanding Default Mock Behavior

What happens if you call a method on a mock without telling it what to do?

  • Objects: Methods returning objects will return null.
  • Primitives: Methods returning primitive types (like int, boolean) will return their default values (0, false).
  • Collections: Methods returning collections will return empty collections.
  • Void: Methods returning void do nothing.

Default Behavior in Action

Let's call a method on our mockEmailService without any configuration. Observe the default return value.

import org.mockito.Mockito;

interface EmailService {
  void sendEmail(String to, String subject, String body);
  String getServiceStatus();
}

public class Main {
  public static void main(String[] args) {
    EmailService mockEmailService = Mockito.mock(EmailService.class);
    
    // Calling a method that returns an object
    String status = mockEmailService.getServiceStatus();
    System.out.println("Default status: " + status);
    
    // Calling a void method (does nothing by default)
    mockEmailService.sendEmail("test@example.com", "Hi", "Hello");
    System.out.println("Void method called (no output)");
  }
}

Creating Mocks with `@Mock`

While Mockito.mock() works, for tests, Mockito offers a more convenient way using the @Mock annotation.

You simply declare a field with @Mock, and Mockito takes care of initializing it into a mock object.

Initializing `@Mock` Annotations

For @Mock annotations to work, you need to tell Mockito to process them. In JUnit 5, this is typically done using the @ExtendWith(MockitoExtension.class) annotation on your test class.

Alternatively, you can manually initialize them using MockitoAnnotations.openMocks(this).

Example: Using `@Mock` Annotation

This example simulates a test class where @Mock is used. Run it to see the mock initialized via MockitoAnnotations.openMocks().

import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

interface DataRepository {
  String fetchData();
}

// Simulate a test class structure
class MyServiceTest {
  @Mock
  DataRepository mockRepository;

  public MyServiceTest() {
    // Manually open mocks for demonstration in main
    MockitoAnnotations.openMocks(this);
  }
}

public class Main {
  public static void main(String[] args) {
    MyServiceTest testInstance = new MyServiceTest();
    System.out.println("Mocked repository: " + testInstance.mockRepository.getClass().getName());
    System.out.println("Default fetch data: " + testInstance.mockRepository.fetchData());
  }
}

Quick Check on Mocks

You want to create a mock object for an interface called PaymentGateway. Which of the following is a correct and common way to do this in Mockito?

Recap: Creating Mocks

You've learned the fundamental ways to create mock objects with Mockito:

  • Use Mockito.mock(ClassToMock.class) for direct creation.
  • Use the @Mock annotation on a field, typically initialized by @ExtendWith(MockitoExtension.class) in JUnit 5.
  • Mocks return default values (null, 0, false) for method calls if not configured otherwise.

Next, we'll learn how to verify that your mocks were called as expected!

Sıkça Sorulan Sorular

“Mockito ile Sahte Nesneler Oluşturma” dersi ücretsiz mi?

Evet — “Mockito ile Sahte Nesneler Oluşturma” 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.

“Mockito ile Sahte Nesneler Oluşturma” dersinde ne öğreneceğim?

Bağımlılıklar için sahte nesneler oluşturmak ve sınanan birimi işbirlikçilerinden yalıtmak üzere Mockito'yu 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 2. dersidir.

“Mockito ile Sahte Nesneler Oluşturma” 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