用途
Drupal Kernel 测试用于在最小化的 Drupal 引导(bootstrap)环境下验证模块逻辑。它介于单元测试与功能测试之间:比单元测试更接近真实运行环境,又不需要启动完整站点或浏览器。
适合测试以下内容:
- 与 Drupal 服务容器交互的服务
- 数据库操作与实体 CRUD
- 钩子(hook)实现
- 配置操作
- 需要真实数据库但不需要完整浏览器的测试
基本结构
测试文件通常放在模块的 tests/src/Kernel/ 目录下,并继承 KernelTestBase:
// tests/src/Kernel/MyServiceTest.php
namespace Drupal\Tests\my_module\Kernel;
use Drupal\KernelTests\KernelTestBase;
use Drupal\node\Entity\Node;
use Drupal\node\Entity\NodeType;
/**
* Tests MyService integration.
*
* @group my_module
*/
final class MyServiceTest extends KernelTestBase {
protected static $modules = [
'system',
'user',
'node',
'field',
'text',
'my_module',
];
protected function setUp(): void {
parent::setUp();
$this->installSchema('system', ['sequences']);
$this->installSchema('node', ['node_access']);
$this->installEntitySchema('user');
$this->installEntitySchema('node');
$this->installConfig('my_module');
// Create content type
NodeType::create(['type' => 'article', 'name' => 'Article'])->save();
}
public function testServiceProcessesNode(): void {
$node = Node::create([
'type' => 'article',
'title' => 'Test Node',
'status' => 1,
]);
$node->save();
$service = $this->container->get('my_module.my_service');
$result = $service->process($node);
$this->assertTrue($result);
}
}
installEntitySchema 与 installSchema
// For entity types (creates entity tables)
$this->installEntitySchema('node');
$this->installEntitySchema('user');
$this->installEntitySchema('taxonomy_term');
$this->installEntitySchema('paragraph');
// For specific table schemas (not entity-based)
$this->installSchema('system', ['sequences', 'key_value']);
$this->installSchema('node', ['node_access']);
// For config from a module's config/install
$this->installConfig('my_module');
$this->installConfig(['node', 'user']);
创建测试用户
use Drupal\user\Entity\User;
$user = User::create([
'name' => 'test_user',
'mail' => 'test@example.com',
'status' => 1,
]);
$user->save();
// Set as current user
$this->setCurrentUser($user);
测试配置
$config = $this->config('my_module.settings');
$this->assertTrue($config->get('enabled'));
// Update config
$this->config('my_module.settings')
->set('enabled', FALSE)
->save();
测试钩子
public function testHookNodePresave(): void {
$node = Node::create(['type' => 'article', 'title' => 'Test']);
$node->save();
// Reload to verify hook ran
$node = Node::load($node->id());
$this->assertEquals('Modified by hook', $node->get('field_processed')->value);
}
适用场景
- 需要验证服务容器中注册的服务行为
- 需要真实数据库支持的实体创建、读取、更新、删除
- 需要验证钩子是否被正确触发
- 需要读写配置对象
- 不需要浏览器交互,但需要比纯单元测试更完整的 Drupal 环境
限制
- 不提供完整浏览器环境,无法测试页面渲染、JavaScript 或用户界面交互
- 需要真实数据库连接
- 需要显式声明依赖模块、安装实体 schema 与配置,否则相关功能不可用
- 资料中未提供关于运行命令、性能开销或与其他测试类型对比的更多细节