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

Внедрение имитаций с помощью @Mock и @InjectMocks

Используйте аннотации Mockito, чтобы подключать имитированные зависимости к тестируемому классу и сокращать объём шаблонного кода настройки.

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

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

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

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

Урок «Внедрение имитаций с помощью @Mock и @InjectMocks» бесплатный?

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

Чему я научусь в уроке «Внедрение имитаций с помощью @Mock и @InjectMocks»?

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

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

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

Сколько времени занимает урок «Внедрение имитаций с помощью @Mock и @InjectMocks»?

Большинство уроков 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