Mockito : how to change referenced parameter ?

1,245 views
Skip to first unread message

Xun Ren

unread,
Aug 2, 2013, 11:29:29 AM8/2/13
to moc...@googlegroups.com
Hello,

I am trying to mock a service class (importService) who has a method importQueries. And this method takes an arraylist as parameter but return void.
Inside this method, it changes the values of the list. So how can I mock the changed list ?

Example :

public void myMethod(request) {
 
List<Query> list = buildQuery(request); //in this list, the queries do not have "Id" because they haven't yet been saved in the database
importService.importQueries(list); //this method saves the queries into database, so all of the Ids are set at this moment

Query query = list.get(0);
long id = query.getId();
//.....then I need id to do some other things

}


You see, I can not mock the "list" because it is created inside "myMethod" and "importService.importQueries" returns void, so I can not use
"mock(importService.importQueries(anyList())).thenReturn(...)".
How do you guys do in this situation, please?

Thanks a lot.
Regards!

Eric Lefevre-Ardant

unread,
Aug 3, 2013, 8:20:01 AM8/3/13
to moc...@googlegroups.com

As always, I tend to believe that mocks show what's wrong in a design. I think, in this case, that you might be better off if your objects are immutable (your importQueries() method might return a list of a ids instead, for example).

If the problem is that importQueries() does not belong to you (preventing you from getting it to work as I suggest), then you should consider providing an intermediate class that works do that. This is, I believe, the approach suggested in "Growing Object Oriented Software", a strongly recommended read.

Remember, you are supposed to use mocks to drive your design, not to patch things up after the design has happened

If you do not wish to change your code, then check out Mockito's Answer:
when(importService.importQueries()).then answer(new Answer(){…})

Eric

--
You received this message because you are subscribed to the Google Groups "mockito" group.
To unsubscribe from this group and stop receiving emails from it, send an email to mockito+u...@googlegroups.com.
To post to this group, send email to moc...@googlegroups.com.
Visit this group at http://groups.google.com/group/mockito.
For more options, visit https://groups.google.com/groups/opt_out.
 
 
Reply all
Reply to author
Forward
0 new messages