Re: [mockito] Can we use when() multiple times in a single test case?

6,409 views
Skip to first unread message

Malte Finsterwalder

unread,
Aug 21, 2012, 5:52:31 PM8/21/12
to moc...@googlegroups.com
That's exactly what mockito does.
The only thing to notice is, that it's not possible to do two
consecutive when calls for the same mock object.
What you need to do instead is chain two thenReturn calls like:

when(obj.method()).thenReturn(3).thenReturn(5)

If this is not your problem, please post a real code example here,
that shows your problem.

Greetings,
Malte

On 21 August 2012 20:54, Syed Muhammad Humayun <smhu...@gmail.com> wrote:
> For example:
> ------------------------
> when(objectOfClassA.someMethod()).thenReturn(null);
> when(objectOfClassB.someMethod()).thenReturn(null);
>
> objectOfClassX.methodInWhichBothMethodsOfClassesABGetCalled();
>
> //verify if respective methods of A and B are called appropriately or not
> ------------------------
>
> is this possible? I'm trying to that but it is not behaving correctly and it
> seems like the framework is unable to remember the mock behavior of first
> when().
>
> ~ Humayun
>
>
> --
> You received this message because you are subscribed to the Google Groups
> "mockito" group.
> To view this discussion on the web visit
> https://groups.google.com/d/msg/mockito/-/tLkfR3be1nIJ.
> To post to this group, send email to moc...@googlegroups.com.
> To unsubscribe from this group, send email to
> mockito+u...@googlegroups.com.
> For more options, visit this group at
> http://groups.google.com/group/mockito?hl=en.

Brice Dutheil

unread,
Aug 22, 2012, 4:58:25 AM8/22/12
to moc...@googlegroups.com
when(objectOfClassA.someMethod()).thenReturn(null);
when(objectOfClassB.someMethod()).thenReturn(null);

There shouldn't be any issue here, as this should be different instances right ?
If not then Malte is correct, you should instead use the consecutive stubbing API.

If you still encounter problems, we'll need more code to identify what's wrong here.


Cheers,
-- Brice
Reply all
Reply to author
Forward
0 new messages