The Active Record Pattern(3) 独立したテスト

<< (2)サンプルコード - 目次に戻る - (4)レコードの作成 >>
http://www.devshed.com/c/a/PHP/The-Active-Record-Pattern/2/の日本語訳

独立したテスト - The Active Record Pattern - Test Independence

テストは互いに独立しているべきです。そうでないと、あるテストの結果がその後のテストの結果に影響を与える可能性があります。

Tests should be independent of each other; otherwise, the mere running of a certain test could interfere with the results of latter tests.

データベースに依存するテスト間の影響を避けるには、各テストメソッド間でデータベース(または特定のテーブルだけ)の削除と再作成をするのが最も良いです。SimpleTestでは、各テストの準備のために標準的なxUnitのsetup()メソッドを使用できます。

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);
  }
}

このコードでは$conn属性に標準的なADOConnectionオブジェクトを設定し、その接続のexecute()メソッドを使ってテーブルの削除と再作成を行うSQL文を実行します。setup()メソッドで実行しいるため、各テストメソッドの開始時にはデータベーステーブルの新しいコピーを使用できます。

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.

さらに、setup()メソッドで基本的な整合性チェックを行うこともできます(ついでにADOConnection APIをもう少し学びます)。

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);
    }
  }
}

ADDdbをあまり知らなくても、execute()メソッドがうまくいくとADOResultSetオブジェクトを返すことがわかるでしょう。このオブジェクトはrecordCount()メソッドを持っており、これを使えばテーブルが空であるか確認できます。レコードセットオブジェクトも同じメソッドで結果セットメタデータを探すことができ、fetchField()を使ってテーブルの構造を確認できます。

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.

<< (2)サンプルコード - 目次に戻る - (4)レコードの作成 >>