_
_
Mockito Cheatsheet¶
• Installation
| 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 |
| _ | |
| oder Grundlegende Befehle |
| 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 |
| _ | |
| Annotationsbasiertes 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 |
| _ | |
| Stumpfmethoden |
| 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 |
| _ | |
| In den Warenkorb |
| 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 |
| _ | |
| Verifikationsmethoden |
| 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
| Command | Description |
|---|---|
| INLINE_CODE_96 | Create argument captor for specified type |
| INLINE_CODE_97 | Capture argument during verification |
| INLINE_CODE_98 | Get the captured argument value |
| INLINE_CODE_99 | Get list of all captured values (multiple calls) |
| INLINE_CODE_100 | Create captor using annotation |
// 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());
```_
Erweiterte Eigenschaften
| Feature | Description |
|---------|-------------|
| __INLINE_CODE_101__ | Create ordered verifier for multiple mocks |
| __INLINE_CODE_102__ | Verify method called in specific order |
| __INLINE_CODE_103__ | Mock static methods (requires mockito-inline) |
| __INLINE_CODE_104__ | Mock constructor calls (requires mockito-inline) |
| __INLINE_CODE_105__ | Mock final classes (requires mockito-inline) |
| __INLINE_CODE_106__ | Create lenient stubbing (won't fail on unused stubs) |
| __INLINE_CODE_107__ | Clear invocation history but keep stubs |
| __INLINE_CODE_108__ | Detect incorrect Mockito usage in tests |
| __INLINE_CODE_109__ | Clear all inline mocks (static/constructor) |
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 |
Konfiguration
### Test Class Setup mit JUnit 5
```java
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 mit 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
}
}
Individuelle Einstellungen¶
// 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 Konfigurationsdatei¶
Erstellen mockito-extensions/org.mockito.plugins.MockMaker in Testressourcen:
Dies ermöglicht das Verspotten von Endklassen und Methoden ohne explizite Abhängigkeit.
Häufige Anwendungsfälle
Use Case 1: Testen von Service Layer mit 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: Testen Ausnahme 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: Verifizierende Methode 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: Erfassen und Beschwören¶
@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: Asynchron testen Code¶
@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 Methoden¶
@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: Verwendung von Spies für 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));
}
oder Best Practices
-
**Use __INLINE_CODE_121_ und
@InjectMocksAnnotations* anstelle von manueller Mock-Erstellung für saubereren Testcode und automatischer Abhängigkeitsinjektion -
Prefer
when().thenReturn()überdoReturn().when()für regelmäßige Verspottung; Verwenden SiedoReturn()nur für Spione oder wenn Sie Methoden, die Ausnahmen werfen -
Mock-Typen, die Sie nicht besitzen (z.B. Bibliotheken von Drittanbietern) - statt, erstellen Sie Wrapper-Schnittstellen und verspotten diejenigen, die Kontrolle über Ihre Testgrenzen zu halten
-
**Verify Verhalten, keine Implementierungsdetails* - konzentrieren Sie sich auf die Prüfung, was der Code tut, nicht wie es es tut; vermeiden Sie Überverifikation, die Tests spröde macht
-
Benutzen Sie Argument captors sparingly - nur, wenn Sie komplexe Argumentwerte geltend machen müssen; bevorzugen Sie Argumentvergleicher für einfache Überprüfung
-
Eine logische Behauptung pro Test - Tests sollten ein einzelnes Verhalten überprüfen, um Fehler leicht zu diagnostizieren und zu halten
-
** statische Mocks richtig aufladen* - Verwenden Sie immer Try-with-Ressourcen, wenn Sie statische Methoden mockieren, um zu verhindern, dass Zustandsleck zwischen Tests
-
Use
lenient()für optionale Stubs - beim Stubbing von Methoden, die nicht in allen Testszenarien genannt werden, markieren Sie sie als Lenient, um unnötige strenge Störfehler zu vermeiden -
**Avoid Mocking Value Objects* - Mock nur Objekte mit Verhalten (Dienste, Repositories); Verwenden Sie reale Instanzen für DTOs, Entitäten und Wertobjekte
-
** Nennen Sie Ihre Mocks deskriptiv* - beim Debuggen komplexer Tests verwenden Sie
mock(Class.class, "descriptiveName"), um Fehlermeldungen deutlicher zu machen
Fehlerbehebung
| 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 |
| _ | |
| -- |
Quick Reference Import Statements:
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;