Repaso
EspaƱol
Spring, JPA & Java WebIntermediateSPR-25

What is Mockito used for in tests?

Options

  1. Running the application in a production environment
  2. Creating mocks for dependencies to test a class alone (Correct option)
  3. Compiling Java source files into bytecode quickly
  4. Managing database schema migrations between versions

Answer

Creating mock objects that stand in for real dependencies, so you test one class in isolation and verify its interactions

Why

Mockito creates fake versions of your dependencies. You tell the mock what to return (when(...).thenReturn(...)) and later verify calls (verify(...)).

This lets you test OrderService without a real database or payment provider.

With JUnit 5: @ExtendWith(MockitoExtension.class), @Mock for fakes and @InjectMocks for the class under test.

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

    @Test
    void chargesTheCustomer() {
        when(gateway.charge(100)).thenReturn(true);
        assertTrue(service.pay(100));
        verify(gateway).charge(100);
    }
}

Remember

Mockito = fake dependencies for isolated unit tests.

Key terms

Practice this question in Repaso