Custom Answers and Callbacks
Implement custom logic for mock method calls using `Answer` interfaces to simulate complex behaviors.
Beyond Simple Stubbing
Sometimes, simply returning a fixed value with when().thenReturn() isn't enough for your mock objects.
- What if a mock method needs to modify an argument passed to it?
- What if it needs to execute a callback function?
- What if its return value depends on multiple inputs in a complex, dynamic way?
These advanced scenarios call for custom logic within your mocks.
Introducing Mockito's Answer
Mockito provides the org.mockito.stubbing.Answer interface. This powerful tool lets you define custom behavior for a mocked method call.
- Think of it as writing a small piece of code that runs whenever the mocked method is invoked.
- The
Answerinterface has a single method:Object answer(Invocation invocation) throws Throwable;.
It gives you fine-grained control over mock responses.
All lessons in this course
- Custom Answers and Callbacks
- Mocking Static Methods and Constructors
- Mockito Best Practices
- Capturing Arguments with ArgumentCaptor