Mockito: Stubbing Methods That Return Type With Bounded Wild-Cards
When stubbing a bounded wildcard generic method in Mockito, use any() and a proper type cast. Below is a short example for stubbing a Number
return:
Note: The <Number>
type part ensures compatibility with the bounded wildcard, so we care about generics and type safety.
Stubbing generics - Decoded 👨💻
Using thenAnswer for dynamic results
If you're dealing with more complex control over the method's response, thenAnswer is your friend. It maintains type safety
, especially useful dealing with generics:
Ensuring type-safe stubbing
Always try to, if not must, use thenAnswer to ensure type safety. In those scenarios where it's a do or die
kind of situation, using doReturn is pardoned:
The flip side of doReturn
A method bypassing type checks? Sounds scary right? But doReturn can be the knight in shining armor in some wildcard situations at the cost of type safety:
Visualization
The concept of stubbing methods with bounded wildcards in Mockito is like socks pairing:
Type-safe list with thenAnswer
For those methods returning lists with complex generics, you can use a similar pattern using thenAnswer:
Collective wisdom
Sometimes, the best way to learn is to learn from others' mistakes. Do take a look at the Mockito Google group for more in-depth and challenging discussions.
Check out the manual
Mockito documentation is a goldmine. It isn't merely about the basics, but about how to think effectively in Mockito's context.
Was this article helpful?