Saltar a contenido

Mockito

_

Mockito Cheatsheet

Instalación

Build Tool Configuration
Maven Add to INLINE_CODE_13:HTML_TAG_153____INLINE_CODE_14____HTML_TAG_154  INLINE_CODE_15____HTML_TAG_155  INLINE_CODE_16____HTML_TAG_156  INLINE_CODE_17____HTML_TAG_157  INLINE_CODE_18____HTML_TAG_158____INLINE_CODE_19
Gradle Add to INLINE_CODE_20:HTML_TAG_159____INLINE_CODE_21
Gradle (Kotlin) Add to INLINE_CODE_22:HTML_TAG_160____INLINE_CODE_23
JUnit 5 Integration Maven: INLINE_CODE_24____HTML_TAG_161__Gradle: __INLINE_CODE_25
Final Classes/Methods Maven: INLINE_CODE_26____HTML_TAG_162__Gradle: __INLINE_CODE_27
Manual JAR Download from Maven Central and add to classpath:HTML_TAG_163__Linux/macOS: __INLINE_CODE_28____HTML_TAG_164__Windows: __INLINE_CODE_29

Comandos básicos

Command Description
INLINE_CODE_30 Create a mock object of the specified class
INLINE_CODE_31 Stub a method to return a specific value
INLINE_CODE_32 Verify that a method was called once
INLINE_CODE_33 Verify method was called exactly n times
INLINE_CODE_34 Verify method was never called
INLINE_CODE_35 Argument matcher for any integer value
INLINE_CODE_36 Argument matcher for any string value
INLINE_CODE_37 Argument matcher for any object of specified class
INLINE_CODE_38 Argument matcher for exact value match
INLINE_CODE_39 Create a spy (partial mock) of a real object
INLINE_CODE_40 Stub void method to throw exception
INLINE_CODE_41 Alternative stubbing syntax (safer for spies)
INLINE_CODE_42 Verify no methods were called on mock
INLINE_CODE_43 Verify no other methods were called after verified ones
INLINE_CODE_44 Clear all stubbing and invocation history

Annotation-Based Setup

Annotation Description
INLINE_CODE_45 Create a mock object automatically
INLINE_CODE_46 Create instance and inject all INLINE_CODE_47 dependencies
INLINE_CODE_48 Create a spy object automatically
INLINE_CODE_49 Create an ArgumentCaptor automatically
INLINE_CODE_50 JUnit 5: Enable Mockito annotations
INLINE_CODE_51 Manually initialize mocks in INLINE_CODE_52 method
INLINE_CODE_53 Create mock with deep stubbing enabled
INLINE_CODE_54 Create named mock for better debugging

Stubbing Methods

Command Description
INLINE_CODE_55 Return different values on consecutive calls
INLINE_CODE_56 Throw exception when method is called
INLINE_CODE_57 Call the real implementation
INLINE_CODE_58 Custom answer with access to invocation details
INLINE_CODE_59 Explicitly stub void method to do nothing
INLINE_CODE_60 Alternative answer syntax for void methods
INLINE_CODE_61 Chain different behaviors
INLINE_CODE_62 Return smart nulls instead of regular nulls
INLINE_CODE_63 Enable deep stubbing for chained calls
INLINE_CODE_64 Configure mock with custom settings

Argument Matchers

Matcher Description
INLINE_CODE_65, INLINE_CODE_66, INLINE_CODE_67 Match any primitive numeric value
INLINE_CODE_68 Match any string value
INLINE_CODE_69, INLINE_CODE_70, INLINE_CODE_71 Match any collection type
INLINE_CODE_72 Match any object of specified type
INLINE_CODE_73, INLINE_CODE_74 Match null or non-null values
INLINE_CODE_75 Match exact value (required when mixing matchers)
INLINE_CODE_76 Match string containing substring
INLINE_CODE_77 Match string starting with prefix
INLINE_CODE_78 Match string ending with suffix
INLINE_CODE_79 Match string against regex pattern
INLINE_CODE_80 Custom argument matcher with lambda
INLINE_CODE_81 Custom matcher for int primitives
INLINE_CODE_82, INLINE_CODE_83, INLINE_CODE_84 Match any primitive value

Métodos de verificación

Command Description
INLINE_CODE_85 Verify method called exactly once
INLINE_CODE_86 Verify method called exactly n times
INLINE_CODE_87 Verify method called at least n times
INLINE_CODE_88 Verify method called at most n times
INLINE_CODE_89 Verify method called one or more times
INLINE_CODE_90 Verify method never called
INLINE_CODE_91 Verify this was the only method called
INLINE_CODE_92 Verify within timeout (async testing)
INLINE_CODE_93 Verify after waiting specified time
INLINE_CODE_94 Combine timeout with invocation count
INLINE_CODE_95 Add custom failure message

Argument Captors

__TABLE_172_

// Example: Capturing and asserting arguments
ArgumentCaptor<User> userCaptor = ArgumentCaptor.forClass(User.class);
verify(userService).save(userCaptor.capture());
User capturedUser = userCaptor.getValue();
assertEquals("John", capturedUser.getName());

Características avanzadas

__TABLE_173_

BDD Style (Behavior-Driven Development)

Command Description
INLINE_CODE_110 BDD-style stubbing (alias for INLINE_CODE_111)
INLINE_CODE_112 BDD-style exception stubbing
INLINE_CODE_113 Alternative BDD syntax for void methods
INLINE_CODE_114 BDD-style exception for void methods
INLINE_CODE_115 BDD-style verification (alias for INLINE_CODE_116)
INLINE_CODE_117 BDD-style verification with count
INLINE_CODE_118 BDD-style no interactions check
INLINE_CODE_119 BDD-style no more interactions check

Configuración

Test Class Setup with JUnit 5

import org.mockito.Mock;
import org.mockito.InjectMocks;
import org.mockito.junit.jupiter.MockitoExtension;
import org.junit.jupiter.api.extension.ExtendWith;
import static org.mockito.Mockito.*;

@ExtendWith(MockitoExtension.class)
class UserServiceTest {

    @Mock
    private UserRepository userRepository;

    @Mock
    private EmailService emailService;

    @InjectMocks
    private UserService userService;

    @Test
    void testUserCreation() {
        User user = new User("John");
        when(userRepository.save(any(User.class))).thenReturn(user);

        User result = userService.createUser("John");

        verify(userRepository).save(any(User.class));
        verify(emailService).sendWelcomeEmail(user);
        assertEquals("John", result.getName());
    }
}

Test Class Setup with JUnit 4

import org.mockito.Mock;
import org.mockito.InjectMocks;
import org.mockito.MockitoAnnotations;
import org.junit.Before;
import org.junit.Test;
import static org.mockito.Mockito.*;

public class UserServiceTest {

    @Mock
    private UserRepository userRepository;

    @InjectMocks
    private UserService userService;

    @Before
    public void setUp() {
        MockitoAnnotations.openMocks(this);
    }

    @Test
    public void testUserCreation() {
        // Test implementation
    }
}

Ajustes de Mock personalizados

// Create mock with custom settings
UserService mock = mock(UserService.class, withSettings()
    .name("customMockName")
    .defaultAnswer(RETURNS_SMART_NULLS)
    .serializable()
    .verboseLogging());

// Create mock with invocation listeners
UserService mock = mock(UserService.class, withSettings()
    .invocationListeners(invocation -> {
        System.out.println("Method called: " + invocation.getMethod());
    }));

Mockito Configuration File

Crear mockito-extensions/org.mockito.plugins.MockMaker en recursos de prueba:

mock-maker-inline

Esto permite burlarse de clases y métodos finales sin dependencia explícita.

Common Use Cases

Use Case 1: Testing Service Layer with Repository

@ExtendWith(MockitoExtension.class)
class UserServiceTest {
    @Mock
    private UserRepository userRepository;

    @InjectMocks
    private UserService userService;

    @Test
    void shouldFindUserById() {
        // Given
        User expectedUser = new User(1L, "John");
        when(userRepository.findById(1L)).thenReturn(Optional.of(expectedUser));

        // When
        User result = userService.getUserById(1L);

        // Then
        assertEquals("John", result.getName());
        verify(userRepository).findById(1L);
    }
}

Use Case 2: Testing Excepción Handling

@Test
void shouldHandleUserNotFoundException() {
    // Given
    when(userRepository.findById(999L))
        .thenThrow(new UserNotFoundException("User not found"));

    // When & Then
    assertThrows(UserNotFoundException.class, () -> {
        userService.getUserById(999L);
    });

    verify(userRepository).findById(999L);
}

Use Case 3: Verifying Method Call Order

@Test
void shouldProcessUserInCorrectOrder() {
    // Given
    User user = new User("John");

    // When
    userService.registerUser(user);

    // Then
    InOrder inOrder = inOrder(userRepository, emailService, auditService);
    inOrder.verify(userRepository).save(user);
    inOrder.verify(emailService).sendWelcomeEmail(user);
    inOrder.verify(auditService).logRegistration(user);
}

Use Case 4: Capturing and Asserting Arguments

@Test
void shouldSaveUserWithCorrectData() {
    // Given
    ArgumentCaptor<User> userCaptor = ArgumentCaptor.forClass(User.class);

    // When
    userService.createUser("John", "john@example.com");

    // Then
    verify(userRepository).save(userCaptor.capture());
    User capturedUser = userCaptor.getValue();
    assertEquals("John", capturedUser.getName());
    assertEquals("john@example.com", capturedUser.getEmail());
    assertNotNull(capturedUser.getCreatedDate());
}

Use Case 5: Testing Asynchronous Código

@Test
void shouldProcessAsyncOperation() {
    // Given
    when(asyncService.processData(anyString()))
        .thenReturn(CompletableFuture.completedFuture("result"));

    // When
    userService.processUserAsync("user123");

    // Then - verify within timeout for async operations
    verify(asyncService, timeout(1000)).processData("user123");
    verify(notificationService, timeout(1000)).sendNotification(any());
}

Use Case 6: Mocking Static Methods

@Test
void shouldMockStaticUtilityMethod() {
    try (MockedStatic<DateUtils> dateUtils = mockStatic(DateUtils.class)) {
        // Given
        LocalDate fixedDate = LocalDate.of(2024, 1, 1);
        dateUtils.when(DateUtils::getCurrentDate).thenReturn(fixedDate);

        // When
        User user = userService.createUser("John");

        // Then
        assertEquals(fixedDate, user.getRegistrationDate());
        dateUtils.verify(DateUtils::getCurrentDate);
    }
}

Use Case 7: Using Spies for Partial Mocking

@Test
void shouldUseSpyForPartialMocking() {
    // Given
    UserService realService = new UserService(userRepository);
    UserService spyService = spy(realService);

    // Stub only specific method
    doReturn(true).when(spyService).isValidEmail(anyString());

    // When
    User user = spyService.createUser("John", "invalid-email");

    // Then - real methods called except stubbed ones
    verify(spyService).isValidEmail("invalid-email");
    verify(userRepository).save(any(User.class));
}

Buenas prácticas

  • Use @Mock y @InjectMocks_ anotaciones en lugar de la creación manual de mock para el código de prueba más limpio y la inyección de dependencia automática

  • **Prefer when().thenReturn()___________________________________ _______________ sólo para espías o cuando se tocan métodos que arrojan excepciones

  • No te burles los tipos que no tienes (por ejemplo, bibliotecas de terceros) - en lugar de eso, crear interfaces de envoltura y burlar a los que mantienen el control sobre tus límites de prueba

  • Verificar el comportamiento, no los detalles de la implementación - centrarse en la prueba de lo que el código hace, no cómo lo hace; evitar la sobre-verificación que hace que las pruebas sean frágiles

  • Use argumentos captores espaciosamente - sólo cuando usted necesita para afirmar valores complejos del argumento; prefiera los coincidentes del argumento para una verificación simple

  • Mantenga una aserción lógica por prueba - las pruebas deben verificar un solo comportamiento para hacer las fallas fáciles de diagnosticar y mantener

  • Clean up static mocks properly - siempre use try-with-resources cuando se burlan de métodos estáticos para evitar fugas estatales entre pruebas

  • Use lenient() para los problemas opcionales - cuando se tocan métodos que podrían no llamarse en todos los escenarios de prueba, marquelos como indulgentes para evitar errores estrictos innecesarios

  • Evitar burlar objetos de valor - burlar sólo objetos con comportamiento (servicios, repositorios); utilizar instancias reales para OD, entidades y objetos de valor

  • Nombre sus medias descriptivamente - al depurar pruebas complejas, utilice mock(Class.class, "descriptiveName") para aclarar los mensajes de error

Troubleshooting

Issue Solution
UnnecessaryStubbingException: Stubbed method not called in test Remove unused stubs or mark as lenient: INLINE_CODE_128
Cannot mock final class/method Add INLINE_CODE_129 dependency or create INLINE_CODE_130 with content INLINE_CODE_131
NullPointerException when calling mocked method Ensure mock is properly initialized with INLINE_CODE_132 or INLINE_CODE_133
ArgumentMatchers can't be used outside stubbing/verification Don't store matcher results in variables; use them directly in INLINE_CODE_134 or INLINE_CODE_135 calls
WrongTypeOfReturnValue: Cannot return X for method returning Y Check return type matches method signature; use correct stubbing method (e.g., INLINE_CODE_136 vs INLINE_CODE_137)
Mixing argument matchers and raw values When using matchers like INLINE_CODE_138, all arguments must use matchers; wrap raw values with INLINE_CODE_139: INLINE_CODE_140
TooManyActualInvocations: Method called more times than expected Verify actual invocation count with INLINE_CODE_141 or check for unintended repeated calls in production code
MockitoException: Cannot instantiate @InjectMocks Ensure class has a no-arg constructor or constructor with all @Mock dependencies; check for final fields without initialization
Spy stubbing causes real method invocation Use INLINE_CODE_142 instead of INLINE_CODE_143 to avoid calling real method during stubbing
Static mock not working Ensure INLINE_CODE_144 dependency is included and use try-with-resources: INLINE_CODE_145
NoSuchMethodError or ClassNotFoundException Check Mockito version compatibility with your JUnit version; ensure all dependencies are consistent
InOrder verification fails unexpectedly Remember that INLINE_CODE_146 only verifies specified interactions; other method calls can occur between verified calls

-...

Declaraciones de importación de referencia rápida:

import static org.mockito.Mockito.*;
import static org.mockito.BDDMockito.*;
import static org.mockito.ArgumentMatchers.*;
import org.mockito.Mock;
import org.mockito.InjectMocks;
import org.mockito.Spy;
import org.mockito.Captor;
import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
import org.mockito.junit.jupiter.MockitoExtension;
import org.junit.jupiter.api.extension.ExtendWith;