liminfo

Mockitoref

Free reference guide: Mockitoref

25 results

About Mockitoref

The Mockito Reference is a comprehensive, searchable cheat sheet for Mockito — the most popular Java mocking framework used in unit and integration testing. The reference is organized into six categories: Mock Objects (mock(), spy(), reset(), framework listeners), Stubbing (when().thenReturn(), thenThrow(), thenAnswer(), doReturn(), chained stubbing), Verification (verify(), times()/never()/atLeast(), verifyNoMoreInteractions(), InOrder, ArgumentCaptor), Argument Matchers (any(), eq(), argThat(), isNull()/isNotNull()), Annotations (@Mock, @InjectMocks, @Spy, @Captor), and Advanced features (lenient(), mockStatic(), mockConstruction()).

Java backend engineers, Spring Boot developers, and Android developers use Mockito extensively for unit testing service layers, controllers, and repositories without requiring a running database or external service. Mockito enables test isolation by replacing real dependencies with mock objects that return controlled values, throw specific exceptions, or record their interactions for later verification. The @InjectMocks annotation automatically wires mocks into the class under test, eliminating boilerplate setup code.

Each entry in this reference provides the exact Mockito method or annotation syntax, a description of what it does, and a realistic Java code example covering common patterns like verifying a repository save() call with ArgumentCaptor, using argThat() for custom assertion logic, chaining thenReturn() calls for consecutive invocations, and using mockStatic() to mock static utility methods introduced in Mockito 3.4. Whether you are writing your first mock test or implementing advanced spy patterns, this reference covers every scenario.

Key Features

  • Six categories: Mock Objects, Stubbing, Verification, Argument Matchers, Annotations, Advanced
  • All stubbing variants: thenReturn(), thenThrow(), thenAnswer() for dynamic responses, doReturn() for spies
  • Verification modes: times(n), never(), atLeast(n), atMost(n), and verifyNoMoreInteractions()
  • InOrder verification for asserting the exact sequence of method calls across multiple mocks
  • ArgumentCaptor to capture and assert on the exact object passed to a mock method
  • JUnit 5 annotations: @Mock, @InjectMocks, @Spy, @Captor with @ExtendWith(MockitoExtension.class)
  • Advanced: mockStatic() for static methods and mockConstruction() for constructor mocking (Mockito 3.4+)
  • Argument matchers: any(), anyString(), eq(), argThat() with lambda predicates, isNull()/isNotNull()

Frequently Asked Questions

What is the difference between mock() and spy() in Mockito?

mock(Class) creates a pure mock object where all methods return default values (null, 0, false, empty list) unless stubbed. spy(object) wraps a real object instance — unstubbed methods delegate to the real implementation, while stubbed methods return the configured value. Use spy() when you need the real behavior for most methods but want to override or verify a subset.

How do I use when().thenReturn() to stub a method?

Use the pattern: when(mockObject.method(args)).thenReturn(value). For example: when(mockUserService.findById(1L)).thenReturn(new User("Kim")). After this, calling mockUserService.findById(1L) returns the User("Kim") object. For void methods or when using a spy, use doReturn(value).when(mock).method() instead to avoid calling the real method during stubbing setup.

What is ArgumentCaptor and when should I use it?

ArgumentCaptor captures the actual argument passed to a mocked method so you can assert on its properties. Use it when the argument is constructed inside the code under test and you cannot easily create an equal instance to pass to verify(). For example: ArgumentCaptor<User> captor = ArgumentCaptor.forClass(User.class); verify(mockRepo).save(captor.capture()); assertEquals("Kim", captor.getValue().getName());

What does @InjectMocks do and how does it work?

@InjectMocks tells Mockito to create an instance of the annotated class and inject all @Mock and @Spy fields into it via constructor injection, setter injection, or field injection (tried in that order). It eliminates the need to manually call new UserService(mockRepo, mockEmailService). The @ExtendWith(MockitoExtension.class) annotation on the test class triggers the injection.

How do I verify that a method was called a specific number of times?

Use verify(mock, times(n)).method(). For example: verify(emailService, times(2)).sendEmail(any()). Other modes include verify(mock, never()).method() to assert a method was never called, verify(mock, atLeast(1)).method() for at least one call, and verify(mock, atMost(3)).method() for no more than three calls.

What is the difference between verify() and verifyNoMoreInteractions()?

verify() checks that a specific method was called with specific arguments. verifyNoMoreInteractions(mock) checks that no other method calls happened beyond what you have already verified. Use it when you want to ensure the code under test does not perform unexpected side effects — for example, confirming it does not send an email when a condition is false.

How does mockStatic() work for testing static methods?

mockStatic() (available since Mockito 3.4) creates a scoped mock for static methods within a try-with-resources block: try (MockedStatic<Utils> mocked = mockStatic(Utils.class)) { mocked.when(Utils::now).thenReturn(fixedTime); /* test code */ }. The static mock is automatically closed and reset after the try block, preventing test pollution.

When should I use argThat() instead of eq() or any()?

Use argThat(predicate) when you need to assert on a complex condition that eq() cannot express — for example, verifying that a User object passed to save() has a name of "Kim" AND an age greater than 18. argThat() accepts a lambda: verify(mock).save(argThat(user -> user.getName().equals("Kim") && user.getAge() > 18)). Use any() when the argument does not matter, and eq(value) when you need exact equality.