关于 drupal-kernel
面向 Drupal 开发者的 Kernel 测试技能,涵盖服务容器、数据库、实体、配置和钩子测试,无需运行完整浏览器测试。
主要功能
- 01服务容器测试
- 02实体与数据库设置
- 03配置断言与更新
- 04钩子行为验证
适用场景
- 01测试使用 Drupal 容器的服务
- 02验证实体 CRUD 与数据库操作
- 03检查配置变更
- 04确认钩子修改已保存实体
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ edutrul/ drupal-ai --skill drupal-kernel安装后在 Claude Code 中输入/drupal-kernel确认已加载。
附带文件README.md
详细介绍
Drupal 内核测试
适用场景
- 测试与 Drupal 服务容器交互的服务
- 数据库操作和实体 CRUD
- 钩子实现
- 配置操作
- 需要真实数据库但不需要完整浏览器环境的测试
基本结构
// 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' => '[email protected]',
'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);
}
评论
支持 Markdown