This post originated from an RSS feed registered with Java Buzz
by Geoffrey Wiseman.
Original Post: "Mock Roles, Not Objects"
Feed Title: Furious Purpose
Feed URL: http://www.jroller.com/diathesis/feed/entries/rss
Feed Description: Thoughts and experiences on technology and software.
Having run into a few references to the Mock Roles, Not Objects
seminar /
paper at OOPSLA '04,
and having done a few searches for it (fruitlessly, at the time), I
eventually asked to see a copy on the jMock mailing list, and was given
a reference to its current location (which Google now shows as well).
There's a lot in there, and I hadn't found the time to finish reading
it until recently. If you're not familiar with jMock, this is a great
way to learn a little more about it, and about the mock objects
approach as a general rule. In particular, this paper focuses on
the idea of using mock objects, and jMock, to help you design your
applications.
Since this is familiar ground for many people who do unit testing,
there was one point in particular that struck me as interesting:
the idea that mocks allow you to do this from a top-down perspective
without writing code that you believe to be fundamentally incorrect.
For instance, imagine that you were about to write a login feature
for a web application. There are a wide array of approaches that
you might take. Let's narrow it down, for the moment, to the
approaches that you could call test-driven (this may not be your
approach, but it's the one that's relevant here).
You might decide,
that from a testability perspective, it's easiest to start at the
conceptual 'bottom'. You might build a test that supplies a username
to a DAO and verifies that a user object is returned with that username
and with the password. You could then build a DAO that performs that
task. You might then build a test for a login service that uses that DAO,
and then that login service. You might then build a servlet that uses that
service, and so forth.
Alternately, you might decide to start at the top and work your way down,
writing a test that runs against the servlet or the service and verifies
that the login is successful. Your first implementation might always return
true. Another test could check for login failure, at which point you
must write something a little more complicated, and so forth. This is the
approach that I most often see associated with TDD.
But what the Mock Roles, Not Objects paper suggests, which seems
reasonable, is that you write the higher level item and, in so doing, you
focus on what API you need the next layer to provide to you. Once you've
developed that API, you can mock it, complete your test, and then move
on to implementing it.
This allows you to focus on the highest-level details and work your way
down, designing the APIs as you need them in exactly as you need them,
and separates the conceptual design of interface you require (or the role)
from the base considerations of the object that implements it.