Making a mocked method return an argument that was passed to it
Mockito enables a mocked method to return its passed argument by utilizing the thenAnswer()
method coupled with a lambda expression. This combination captures argument values using InvocationOnMock::getArguments
and makes this possible. Behold the examples:
This brief code sets the myMethod
to return its first string argument. The joy here? No extra Answer interface implementation. Only simple and short lambdas.
Dynamic stubbing made easy with thenAnswer()
thenAnswer()
method provides dynamic stubbing capabilities in Mockito. It helps you extend mocking needs beyond simple returns. Find here an advanced simulation of a dynamic echo:
How to handle various argument types with Mockito
Your method could accept multiple argument types, and Mockito offers a solution for all:
Simple mocking with returnsFirstArg()
When you need only the first argument, Mockito lets you cut the chase with returnsFirstArg()
:
Void methods? No worries. Use doAnswer()
For void methods, use doAnswer()
:
Confirm mock behavior with assertions
We use assertions to verify if our mock behaves as expected. Here's how:
And for void methods with side effects, validate their changes like so:
Customizing mock's behavior with Answer
Answer
interface in Mockito allows you to create complex behaviors. Here's an example:
Perfecting argument matching with Mockito
Flexibility is crucial in testing different scenarios. Argument matchers in Mockito offer exactly this. Here's how to do it:
Testing data persistence with mocks
Mocking in Mockito goes a long way to simulate data retrieval scenarios. Consider the following map that mimics a database:
Just add data to mockDatabase
during testing for data presence and absence.
Was this article helpful?