Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't return Class Object with Mockito

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?

like image 718
CorayThan Avatar asked Jun 03 '13 04:06

CorayThan


People also ask

How do I return an object in Mockito?

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.

How to mock any object in Mockito?

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.

What is eq() in Mockito?

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) .

What is the difference between doReturn and thenReturn?

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 .


1 Answers

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(); 
like image 65
tasontag Avatar answered Oct 08 '22 04:10

tasontag