0Pricing
Testing Mastery: JUnit, Mockito & Integration Tests · Lección

Inyección de mocks con @Mock y @InjectMocks

Use las anotaciones de Mockito para conectar dependencias simuladas en la clase bajo prueba y reducir el código repetitivo de configuración.

Inyección de mocks con @Mock y @InjectMocks es una lección gratuita de Testing Mastery: JUnit, Mockito & Integration Tests en CoddyKit. Esta es la lección 4 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Testing Mastery: JUnit, Mockito & Integration Tests, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Testing Mastery: JUnit, Mockito & Integration Tests incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en inglés.

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

Preguntas frecuentes

¿La lección «Inyección de mocks con @Mock y @InjectMocks» es gratis?

Sí — el texto completo de «Inyección de mocks con @Mock y @InjectMocks» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Testing Mastery: JUnit, Mockito & Integration Tests, actualiza a CoddyKit PRO. El curso de Testing Mastery: JUnit, Mockito & Integration Tests incluye 4 lecciones en total.

¿Qué aprenderé en «Inyección de mocks con @Mock y @InjectMocks»?

Use las anotaciones de Mockito para conectar dependencias simuladas en la clase bajo prueba y reducir el código repetitivo de configuración. Practicas Testing Mastery: JUnit, Mockito & Integration Tests con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar Testing Mastery: JUnit, Mockito & Integration Tests?

No se requiere experiencia previa. Testing Mastery: JUnit, Mockito & Integration Tests en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 4 de 4.

¿Cuánto tiempo toma la lección «Inyección de mocks con @Mock y @InjectMocks»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de Testing Mastery: JUnit, Mockito & Integration Tests?

Sí. Cada lección de Testing Mastery: JUnit, Mockito & Integration Tests incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Mocks, stubs y fakes
  2. Creación de mocks con Mockito
  3. Verificación de interacciones con mocks
  4. Inyección de mocks con @Mock y @InjectMocks
← Volver a Testing Mastery: JUnit, Mockito & Integration Tests