关于 drupal-unit
面向 PHP 开发者的 Drupal 单元测试参考,适用于测试不依赖 Drupal 运行时服务的逻辑,并提供 PHPUnit 模拟示例和模块测试命令。
主要功能
- 01识别适合单元测试的纯 PHP 逻辑
- 02PHPUnit 模拟示例
- 03模拟 Drupal 翻译
- 04设置日志记录器预期
- 05运行模块测试的命令
适用场景
- 01测试实用函数和数据转换
- 02测试依赖项已模拟的类
- 03检查预期的日志消息
- 04运行单个模块的单元测试
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ edutrul/ drupal-ai --skill drupal-unit安装后在 Claude Code 中输入/drupal-unit确认已加载。
附带文件README.md
详细介绍
Drupal 单元测试
适用场景
- 不依赖 Drupal 的纯 PHP 逻辑
- 实用函数、数据转换、值对象
- 所有依赖都可以模拟的类
基本结构
// tests/src/Unit/MyServiceTest.php
namespace Drupal\Tests\my_module\Unit;
use Drupal\Tests\UnitTestCase;
use Drupal\my_module\Service\MyService;
use Psr\Log\LoggerInterface;
/**
* @coversDefaultClass \Drupal\my_module\Service\MyService
* @group my_module
*/
final class MyServiceTest extends UnitTestCase {
private MyService $service;
protected function setUp(): void {
parent::setUp();
$logger = $this->createMock(LoggerInterface::class);
$this->service = new MyService($logger);
}
/**
* @covers ::processData
*/
public function testProcessData(): void {
$input = ['foo' => 'bar'];
$result = $this->service->processData($input);
$this->assertArrayHasKey('processed', $result);
$this->assertTrue($result['processed']);
}
/**
* @covers ::processData
*/
public function testProcessDataWithEmptyInput(): void {
$this->expectException(\InvalidArgumentException::class);
$this->service->processData([]);
}
}
使用 PHPUnit 创建模拟对象
// Mock a simple interface
$mock = $this->createMock(SomeInterface::class);
$mock->method('someMethod')->willReturn('value');
// Mock with argument matching
$mock->expects($this->once())
->method('someMethod')
->with($this->equalTo('expected-arg'))
->willReturn('result');
// Mock throwing exception
$mock->method('someMethod')->willThrowException(new \RuntimeException('Error'));
// Stub multiple calls
$mock->method('someMethod')
->willReturnMap([
['arg1', 'result1'],
['arg2', 'result2'],
]);
模拟 Drupal 翻译(t())
// UnitTestCase provides getStringTranslationStub()
$this->service = new MyService(
$this->getStringTranslationStub()
);
模拟日志记录器
// Expect a specific log message
$logger = $this->createMock(LoggerInterface::class);
$logger->expects($this->once())
->method('error')
->with($this->stringContains('Failed to process'));
运行测试
示例假设项目使用基于 docroot/ 的 Drupal 项目结构。如果项目使用 web/ 或其他文档根目录,请相应调整路径。
# Run specific test file
ddev exec vendor/bin/phpunit docroot/modules/custom/my_module/tests/src/Unit/MyServiceTest.php
# Run all unit tests for a module
ddev exec vendor/bin/phpunit docroot/modules/custom/my_module/tests/src/Unit/
# Run with verbose output
ddev exec vendor/bin/phpunit --verbose docroot/modules/custom/my_module/tests/
评论
支持 Markdown