Recursive mocking

1,051 views
Skip to first unread message

CowOfDoom

unread,
Sep 24, 2008, 9:57:00 PM9/24/08
to mockito
I have quite a few places in my code where a line of code exists that
looks like this:

if( userService.getUserByUsername(input).getRole().isAdminUser()) {
...
}

If I want to test this bit of code with Mockito, I have to do
something like this:

UserService mockUserService = mock(UserService.class);
UserObject mockUser = mock(UserObject.class);
stub(mockUserService.getUserByUsername("fred")).toReturn(mockUser);
Role mockRole = mock(Role.class);
stub(mockUser.getRole()).toReturn(role);
stub(mockRole.isAdminUser()).toReturn(true);

I was wondering about ways to shorten that call to something like:

UserService mockUserService = mock(UserService.class);
stub( mockUserService.getUserByUsername("fred").getRole().isAdminUser() ).toReturn(true);

which would have the property of creating several mock objects, each
one with exactly one stubbed method returning the next one in the
sequence. I'm wondering whether such a thing would be useful to
others (it'd be very useful in my code base, but maybe that means it's
a lousy code base), and what such a syntax might have to look like if
it could be implemented at all. Thoughts?

Per Lundholm

unread,
Sep 25, 2008, 3:07:38 AM9/25/08
to moc...@googlegroups.com
With all respect for your post, I suggest refactoring the UserService:

userService.isAdminUser(input)

will make it easier to test.

I recommend Michael Feathers book "Working effectivley with legacy code" for advice on refactoring for testability.

/Per

Igor Czechowski

unread,
Sep 25, 2008, 5:06:20 AM9/25/08
to moc...@googlegroups.com
What Per suggested is also know as LoD(Law of Demeter) and you can
read more about it here
http://en.wikipedia.org/wiki/Law_of_Demeter

Igor

Reply all
Reply to author
Forward
0 new messages