Drupal中引入了单元测试框架,那就是simpletest,这个我只是听说过,但是从来没有用过,今天,学习OG模块的时候,发现这个模块里面包含了测试代码,打开一看,测试代码中的格式,和JAVA中的JUNIT非常相似。
我摘一个简单的,给大家看看:
require_once drupal_get_path('module', 'og') . '/tests/og_testcase.php';
class OgPost extends OgTestCase {
/**
* Implementation of getInfo().
*/
function getInfo() {
return array(
'name' => t('Organic groups posting test'),
'description' => t('Tests posting a group post into a group node.'),
'group' => t('Organic groups'),
);
}
/**
* Implementation of setUp().
*/
function setUp() {
parent::setUp('og', 'og_access');
// Create a user with admin permissions.
$web_admin = $this->drupalCreateUser(array('administer nodes', 'administer content types', 'access administration pages', 'administer site configuration', 'administer organic groups'));
$this->drupalLogin($web_admin);
}
/**
* Test the simple case of creation of a group node and a group post
* by the same user.
*/
function testOgPost() {
// Create a group node content type.
$og_group_type = $this->drupalCreateContentType();
variable_set('og_content_type_usage_'. $og_group_type->name, 'group');
// Create a group post content type.
$og_post_type = $this->drupalCreateContentType();
variable_set('og_content_type_usage_'. $og_post_type->name, 'group_post_standard');
// Rebuild the menu so the new content types will appear in the menu.
menu_rebuild();
// Create a group node.
$gid = $this->addOgGroup($og_group_type->name);
// Create a post node.
$this->addOgPost($og_post_type->name, array($gid));
}
}
这里面的测试,使用的是测试类,这个测试类继承了OgTestCase,在这个类中,首先是setUp函数,用来对测试进行初始化。测试方法为testOgPost(),这里以test开头,而在测试方法里面,首先是构建各种测试数据,然后再调用这个ogPost方法。
这个讨论和JUNit中的是完全一样的,可能没有JAVA中的单元测试完善,但是Drupal中,引入自己的单元测试模块,对于代码的质量,无疑会加了一层保险。
相关链接: http://www.thinkindrupal.com
Drupal 7中,Simpletest模块,已经进入了Drupal内核。