0Pricing
Testing Mastery: JUnit, Mockito & Integration Tests · Урок

Моки, заглушки и имитации

Различайте тестовые замены: моки, заглушки, имитации и пустые объекты, а также понимайте их роль в тестировании.

«Моки, заглушки и имитации» — бесплатный урок Testing Mastery: JUnit, Mockito & Integration Tests на CoddyKit. Это урок 1 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Testing Mastery: JUnit, Mockito & Integration Tests, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Testing Mastery: JUnit, Mockito & Integration Tests содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

What are Test Doubles?

When testing a class, it often depends on other classes. These "dependencies" can make tests tricky! Test doubles are stand-in objects that mimic the behavior of real dependencies.

They help isolate the code you're testing, making your tests faster, more reliable, and easier to write.

Why Do We Need Them?

Imagine testing a class that sends emails or talks to a database. You don't want your tests to:

  • Actually send emails (spam!).
  • Slow down by hitting a real database.
  • Depend on external services that might be unavailable.

Test doubles solve these problems by providing controlled, predictable replacements.

Dummy Objects: Just Placeholders

A Dummy Object is the simplest kind of test double. It's passed around but never actually used.

Think of it as a required parameter that your code doesn't care about in a specific test scenario. It just fills a slot.

  • Often null or an empty instance.
  • No behavior is expected from it.
  • Used when an argument is needed but irrelevant for the test.

Dummy Example: Irrelevant Data

Consider a UserService that needs an EmailSender but in a test scenario, we only care about user creation, not email sending.

Here, a null or a basic new EmailSender() might act as a dummy.

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

class UserService {
  private EmailSender emailSender;

  public UserService(EmailSender emailSender) {
    this.emailSender = emailSender;
  }

  public boolean createUser(String username) {
    // In this specific test, we don't care about emailSender
    // emailSender.sendEmail(username + "@example.com", "Welcome", "Hi!");
    return true; // Simplified for example
  }
}

public class Main {
  public static void main(String[] args) {
    // Here, null acts as a dummy object for createUser test
    EmailSender dummySender = null;
    UserService userService = new UserService(dummySender);
    boolean created = userService.createUser("testuser");
    System.out.println("User created: " + created);
  }
}

Stub Objects: Canned Responses

A Stub Object provides pre-programmed answers to method calls during a test. It doesn't perform any real logic; it just returns specific values.

Stubs are great when your test needs a dependency to return a particular piece of data to proceed.

  • Returns fixed, predetermined values.
  • Focuses on state-based testing.
  • Doesn't verify interactions, just supplies data.

Stub Example: Fixed Data

Let's say a ProductService needs a ProductRepository to find products. A stub can return a specific product without hitting a real database.

interface ProductRepository {
  String findProductNameById(int id);
}

class ProductRepositoryStub implements ProductRepository {
  @Override
  public String findProductNameById(int id) {
    if (id == 1) {
      return "Laptop";
    }
    return "Unknown Product";
  }
}

class ProductService {
  private ProductRepository repository;

  public ProductService(ProductRepository repository) {
    this.repository = repository;
  }

  public String getProductDetails(int productId) {
    return "Product: " + repository.findProductNameById(productId);
  }
}

public class Main {
  public static void main(String[] args) {
    ProductRepository stub = new ProductRepositoryStub();
    ProductService service = new ProductService(stub);
    System.out.println(service.getProductDetails(1));
    System.out.println(service.getProductDetails(2));
  }
}

Fake Objects: Light Implementations

A Fake Object has a working implementation, but it's simplified compared to the real one. It typically takes shortcuts that make it unsuitable for production but perfect for tests.

An in-memory database or a file system replacement are common examples of fakes.

  • Contains some logic, not just canned responses.
  • Simulates real behavior, but in a simpler way.
  • Useful for integration-like unit tests.

Fake Example: In-Memory DB

Here's a fake UserRepository that stores users in a simple HashMap instead of a real database. It simulates adding and finding users.

import java.util.HashMap;
import java.util.Map;

interface UserRepository {
  void addUser(String name);
  String findUser(String name);
}

class InMemoryUserRepository implements UserRepository {
  private Map<String, String> users = new HashMap<>();

  @Override
  public void addUser(String name) {
    users.put(name, name);
  }

  @Override
  public String findUser(String name) {
    return users.get(name);
  }
}

class UserService {
  private UserRepository repository;

  public UserService(UserRepository repository) {
    this.repository = repository;
  }

  public void registerUser(String username) {
    repository.addUser(username);
  }

  public boolean userExists(String username) {
    return repository.findUser(username) != null;
  }
}

public class Main {
  public static void main(String[] args) {
    UserRepository fakeRepo = new InMemoryUserRepository();
    UserService service = new UserService(fakeRepo);

    service.registerUser("Alice");
    System.out.println("Alice exists: " + service.userExists("Alice"));
    System.out.println("Bob exists: " + service.userExists("Bob"));
  }
}

Mock Objects: Behavior Verification

A Mock Object is a special type of stub that also records interactions. You use mocks to verify that a specific method was called on a dependency, with specific arguments, and a certain number of times.

Mocks are central to behavior-driven testing, where you care about how your object interacts with its collaborators.

  • Records method calls and arguments.
  • Allows verification of interactions.
  • Often created by mocking frameworks (like Mockito!).

Mocks vs. Stubs: Behavior or State?

The main difference lies in their purpose:

  • Stubs: Focus on state verification. They provide data needed for the test to run, and the test asserts on the state of the system under test.
  • Mocks: Focus on behavior verification. They verify that the system under test interacted with its dependencies in a specific way.

You often combine them: a stub provides data, and a mock verifies an action.

Test Double Check

Which type of test double is primarily used to verify that a specific method was called on a dependency?

Recap: The Test Double Family

We've explored the different types of test doubles and why they're essential for writing good tests:

  • Dummy: A placeholder, passed but not used.
  • Stub: Provides canned answers to method calls.
  • Fake: A simplified working implementation.
  • Mock: Verifies interactions and behavior.

Understanding these helps you choose the right tool for isolating and testing your code effectively. Next, we'll dive into how Mockito helps us create these mocks!

Часто задаваемые вопросы

Урок «Моки, заглушки и имитации» бесплатный?

Да — полный текст урока «Моки, заглушки и имитации» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Testing Mastery: JUnit, Mockito & Integration Tests, подпишись на CoddyKit PRO. Курс Testing Mastery: JUnit, Mockito & Integration Tests содержит 4 уроков всего.

Чему я научусь в уроке «Моки, заглушки и имитации»?

Различайте тестовые замены: моки, заглушки, имитации и пустые объекты, а также понимайте их роль в тестировании. Ты практикуешь Testing Mastery: JUnit, Mockito & Integration Tests с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать Testing Mastery: JUnit, Mockito & Integration Tests?

Предыдущий опыт не требуется. Testing Mastery: JUnit, Mockito & Integration Tests на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 1 из 4.

Сколько времени занимает урок «Моки, заглушки и имитации»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке Testing Mastery: JUnit, Mockito & Integration Tests?

Да. Каждый урок Testing Mastery: JUnit, Mockito & Integration Tests включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Моки, заглушки и имитации
  2. Создание моков с Mockito
  3. Проверка взаимодействий с моками
  4. Внедрение имитаций с помощью @Mock и @InjectMocks
← Назад к Testing Mastery: JUnit, Mockito & Integration Tests