I'm trying to write a unit test, and to do that I'm writing a when statement for a Mockito mock, but I can't seem to get eclipse to recognize that my return value is valid.
Here's what I'm doing:
Class<?> userClass = User.class; when(methodParameter.getParameterType()).thenReturn(userClass);
The return type of .getParameterType()
is Class<?>
, so I don't understand why eclipse says, The method thenReturn(Class<capture#1-of ?>) in the type OngoingStubbing<Class<capture#1-of ?>> is not applicable for the arguments (Class<capture#2-of ?>)
. It offers to cast my userClass, but that just makes some garbled stuff eclipse says it needs to cast again (and can't cast).
Is this just an issue with Eclipse, or am I doing something wrong?
In Mockito, you can specify what to return when a method is called. That makes unit testing easier because you don't have to change existing classes. Mockito supports two ways to do it: when-thenReturn and doReturn-when . In most cases, when-thenReturn is used and has better readability.
Mockito allows us to create mock objects and stub the behavior for our test cases. We usually mock the behavior using when() and thenReturn() on the mock object.
eq(obj) checks that the argument equals obj according to its equals method. This is also the behavior if you pass in real values without using matchers. Note that unless equals is overridden, you'll see the default Object. equals implementation, which would have the same behavior as same(obj) .
One thing that when/thenReturn gives you, that doReturn/when doesn't, is type-checking of the value that you're returning, at compile time. However, I believe this is of almost no value - if you've got the type wrong, you'll find out as soon as you run your test. I strongly recommend only using doReturn/when .
Also, a slightly more terse way to get around this is to use the do syntax instead of when.
doReturn(User.class).when(methodParameter).getParameterType();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With