33.7. Split Domain and Data Source LayersNow that some of the tests were running directly against the API, they were somewhat faster. The database access times were now the bottleneck. We don't follow Emily and Neo as they tackle this problem, because it takes us well away from Fit, but we do give some general guidelines. Carrying out tests when the domain objects include code for managing persistence is more difficult. The dependency between the objects and the databaseor file system or whatevermay mean that a database connection is needed, even if the tests don't involve the database. Database or file access will slow down the tests, which becomes significant as the number of Fit tests grows into hundreds. The problem gets worse when a domain object refers to many other objects that are also persisted to the database. The solution is similar to the one noted earlier.
This untangling can have positive benefits beyond testing. For example, it may be possible to use a tool that automatically manages the mapping from the domain objects to the persistence store, getting rid of a lot of tedious code. Or it may be possible to autogenerate some of the persistence layer, using reflection on the domain objects. See Fowler [Fow02a] for further details of managing persistence in a layered fashion. Once we have separated the data source layer, we can more easily manage the creation of objects from our fixtures during testing. For many tests, we can create temporary domain objects that are needed in the tests but don't need to be written to the database. However, we still need some end-to-end tests, and that involves access to the database, as there is much scope for bugs in the SQL and code that manages that layer. Once the layers are separated, it is much easier to also use unit tests for the interaction between those bottom two layers. Relevant to this process is [FS03], which discusses the evolution of database design. The next hurdle is that many of our domain objects have references to other objects. To create a domain object for testing, we need to create a lot of other objects as well. Much of the time, they are irrelevant to our tests. Questions & Answers
|