This article, the first of two parts, helps you use design patterns to better organize how your web application interacts with a database. It is excerpted from chapter 14 of the book php|architect's Guide to PHP Design Patterns, written by Jason E. Sweat (php|architect, 2005; ISBN: 0973589825).
Tests should be independent of each other; otherwise, the mere running of a certain test could interfere with the results of latter tests.
To avoid interference between tests that rely on a database, it's best to drop and recreate the database (or just specific tables) between each test method. SimpleTest provides the standard xUnit setup() method to prepare for each test.
Here's how you might "reset" the database between each test:
class ActiveRecordTestCase extends UnitTestCase { protected $conn; function __construct($name='') { $this->UnitTestCase($name); $this->conn = DB::conn(); } function setup() { $this->conn->execute('drop table bookmark'); $this->conn->execute(BOOKMARK_TABLE_DDL); } }
The code populates the $conn attribute with a standard ADOConnection object and then uses the connection's execute() method to perform SQL statements dropping and recreating the table. Because this is in the setup() method, each test method starts out with a fresh copy of the database table to work with.
Going a little further, you can do some basic sanity checks of the setup() method (and learn a little bit about the ADOConnection API along the way):
class ActiveRecordTestCase extends UnitTestCase { // ... function testSetupLeavesTableEmptyWithCorrectStructure() { $rs = $this->conn->execute('select * from bookmark'); $this->assertIsA($rs, 'ADORecordSet'); $this->assertEqual(0,$rs->recordCount()); foreach(array( 'id', 'url', 'name', 'description', 'tag', 'created', 'updated') as $i => $name) { $this->assertEqual($name, $rs->fetchField($i)->name); } } }
Even if you're unfamiliar with ADOdb, you can probably still discern that the execute() method returns an ADORecordSet object if successful. The object has a recordCount() method, which is used here to verify the table is empty. The record set object also has some methods to explore result set metadata and the fetchField() is used to verify the structure of the table.