0PricingLogin
Testing Mastery: JUnit, Mockito & Integration Tests · Lesson

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 Answer interface has a single method: Object answer(Invocation invocation) throws Throwable;.

It gives you fine-grained control over mock responses.

All lessons in this course

  1. Custom Answers and Callbacks
  2. Mocking Static Methods and Constructors
  3. Mockito Best Practices
  4. Capturing Arguments with ArgumentCaptor
← Back to Testing Mastery: JUnit, Mockito & Integration Tests