Changing values of objects passed to mocks

5,305 views
Skip to first unread message

Todd

unread,
Jun 30, 2010, 9:47:57 PM6/30/10
to mockito
Hi all,
I've been using Mockito for a while and I love it, it makes my
testing much cleaner and easier. I've found one mock I can't seem to
figure out. Our service tier calls our data access tier. Our access
tier assigns Id's to objects when they're saved. I need to hook into
a callback so that I can modify arguments that are passed to my mock
at runtime. I found this, but it doesn't quite do what I want.

http://mockito.googlecode.com/svn/tags/latest/javadoc/org/mockito/Mockito.html#11


Basically, here's the flow I need.


public void save(Entity e)


mock save with given argument to set the ID into the argument e

use that argument (e.getId()) in assertions in my other tests

The issue is that save(Entity e) changes the state of e, which the
caller then uses. In my case, the caller is the service tier I'm unit
testing. his is very common with data access frameworks. What's the
best was to do this?

szczepiq

unread,
Jul 1, 2010, 4:04:33 AM7/1/10
to moc...@googlegroups.com
Hey,

How about this:

doAnswer(new AssignID(10)).when(daoMock).save(any());

Implement AssignID class to do whatever you like with the arguments passed to the mock. Then you can play with 'extract method' to make it a bit cleaner:

assignID(10).when(daoMock).save(any());

Cheers,
Szczepan


--
You received this message because you are subscribed to the Google Groups "mockito" group.
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.


Todd Nine

unread,
Jul 1, 2010, 3:58:44 PM7/1/10
to moc...@googlegroups.com
Thanks for that Szczepan. Dumb question, but do I simply create my own
static method to create the "extract method", or is there some mockito
magic I can utilize?

> +unsub...@googlegroups.com.


> For more options, visit this group at
> http://groups.google.com/group/mockito?hl=en.
>
>
>
>
> --
> You received this message because you are subscribed to the Google
> Groups "mockito" group.
> To post to this group, send email to moc...@googlegroups.com.
> To unsubscribe from this group, send email to mockito

> +unsub...@googlegroups.com.


> For more options, visit this group at
> http://groups.google.com/group/mockito?hl=en.

todd
SENIOR SOFTWARE ENGINEER

todd nine| spidertracks ltd | 117a the square
po box 5203 | palmerston north 4441 | new zealand
P: +64 6 353 3395 | M: +64 210 255 8576
E: to...@spidertracks.co.nz W: www.spidertracks.com


szczepiq

unread,
Jul 2, 2010, 7:46:45 AM7/2/10
to moc...@googlegroups.com
Your own method. No Mockito magic this time :)

To unsubscribe from this group, send email to mockito+u...@googlegroups.com.
Reply all
Reply to author
Forward
0 new messages