Unittests and external data....

Steven Taschuk staschuk at telusplanet.net
Wed Mar 19 21:40:27 EST 2003


Quoth mcherm at mcherm.com:
  [...]
> I have been trying to address this for a while now, and I
> think I've come up with an approach that works for me. If
> you like to do test-driven development (write the tests
> first), then I can't help you... I couldn't find a sensible
> way to do that, because in the usual case I don't REALLY
> trust that I understand the behavior of the external system
> (the database in this example) until I've tested it. For
> some reason the databases (and other systems) that I use
> keep not behaving exactly according to spec (or what I
> thought the spec was).

Hm.  That's not a problem for unit testing, really; it's a problem
for integration testing.  But it is true that it's difficult to do
test-first development on code which is tightly coupled to an
external system, such as database access code.  (SQL ought to give
you loose coupling, but in practice it doesn't, sadly.)

The problem can be much reduced by writing an abstraction layer on
top of your database code.  This layer then becomes the natural
cut-out point for mocking (among other things, such as storing
your data in different kinds of databases, and maybe even caching
and connection pooling, etc.).  Everything outside that layer can
be developed test-first and unit tested in isolation from the
database.

And, in fact, there's some advantage to doing almost all
development with the mock, deferring writing the real database
access code until the interface has stabilized.

  [...]
> I don't particularly like having the factory functions behave
> differently under unittesting, but that's the best solution
> I've come up with.

Why not just pass in the factory function as a parameter to the
code that needs it (with a default value, naturally)?  The testing
code can then just pass in its own mock version.

-- 
Steven Taschuk                          staschuk at telusplanet.net
"Its force is immeasurable.  Even Computer cannot determine it."
                           -- _Space: 1999_ episode "Black Sun"





More information about the Python-list mailing list