在许多模块中不同的测试实例需要在不同的上下文中运行。比如,一组测试可能需要将测试数据写入数据库;另一组也许需要产生模块表,但找过模块的_install函数。
DrupalWebTestCase和DrupalUnitTestCase 可以扩展来处理这些情况。你可以在modules/simpletest/tests/database_test.test文件中查看这种方法。
集中创建用于测试的样本数据
为了取得一致和节省时间,你可以在一个类中产生所有的样本数据,然后让你的测试实例来继承。
<?php
class MyModuleWebTestCase extends DrupalWebTestCase {
  function setUp() {
    parent::setUp('mymodule');
    // Insert your data into the database here
    // Use db_insert() etc. Hard coded SQL will affect your actual drupal installation, not your test environment
  }
}
class MyModuleExampleTestCase extends MyModuleWebTestCase {
  // No setUp() function necessary, because the setUp is inherited
  public static function getInfo() {
    ...
  }
  function testExample() {
    // Your test(s) here
  }
}
?>
注:在你的父类(MyModuleWebTestCase 以上)不要声明getInfo()或任何测试方法(如:testExample()),否则会产生错误。
模块化你的测试实例
最好的测试实例是小型模块化--在测试实例中,每一种方法如testExample()应该能测试小片代码或功能。
测试数据库不要增加模块安装开销
这是种高级技术,大多数测试者不需要用到。
测试不需要任何数据库功能,只需要扩展DrupalUnitTestCase,但如果需要测试你的模块和数据库的交互而不启用整个模块,你可以使用drupal_install_schema() 函数来创建所需表格。
<?php
class MyModuleDatabaseTestCase extends DrupalWebTestCase {
  function setUp() {
    // Create the module's tables without running hook_install or hook_enable
    drupal_install_schema('mymodule');
  }
}
class MyModuleSchemaTestCase extends MyModuleDatabaseTestCase {
  // No setUp() function necessary, because the setUp is inherited
  public static function getInfo() {
    return array(
      'name' => 'Database functions test',
      'description' => 'Tests CRUD functions',
      'group' => 'My Module',
    );
  }
  /*
   * Tests that parent class created module tables
   */
  function testSchemaCreated() {
    // Your test(s) here
  }
}
?>