命令行测试
测试概述
命令行模块的测试分两个层次:
- 命令逻辑测试: 直接实例化命令,用 Symfony 的
CommandTester驱动输入输出 - 注册装配测试: 验证命令被正确收集、命令名校验生效(覆盖
ConsoleApplicationConfiguration的行为)
命令实例由容器创建,因此命令的构造函数依赖可以用任意测试替身替换。
单元测试
用 CommandTester 测试命令
CommandTester 是 Symfony Console 自带的测试工具,无需启动容器即可运行命令:
php
<?php
declare(strict_types=1);
namespace App\Tests\Command;
use App\Command\HelloCommand;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Console\Tester\CommandTester;
class HelloCommandTest extends TestCase
{
public function testGreetsTheGivenName(): void
{
$command = new HelloCommand();
$tester = new CommandTester($command);
$tester->execute(['name' => 'kuiper']);
$display = $tester->getDisplay();
$this->assertStringContainsString('hello, kuiper', $display);
$this->assertSame(0, $tester->getStatusCode());
}
}测试带依赖注入的命令
命令构造函数的依赖在测试里手工传入(用 mock 或测试替身):
php
<?php
declare(strict_types=1);
namespace App\Tests\Command;
use App\Command\CountUserCommand;
use App\Service\UserService;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Console\Tester\CommandTester;
class CountUserCommandTest extends TestCase
{
public function testOutputsUserCount(): void
{
$userService = $this->createMock(UserService::class);
$userService->method('count')->willReturn(42);
$command = new CountUserCommand($userService);
$tester = new CommandTester($command);
$tester->execute([]);
$this->assertSame("42\n", $tester->getDisplay());
}
}集成测试
测试命令注册
验证 #[AsCommand] 组件、application.commands 配置等注册路径时,参照 kuiper/console 自身的测试方式:用 ComponentScanner 扫描测试目录,构建 ConsoleApplicationConfiguration,再从 Symfony Console 应用上取命令。
php
<?php
declare(strict_types=1);
namespace App\Tests\Command;
use Composer\Autoload\ClassLoader;
use kuiper\di\ComponentCollection;
use kuiper\di\ComponentScanner;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Console\Application as SymfonyConsoleApplication;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\BufferedOutput;
class CommandRegistrationTest extends TestCase
{
protected function setUp(): void
{
parent::setUp();
ComponentCollection::clearInstance();
$this->scanFixtures();
}
protected function tearDown(): void
{
ComponentCollection::clearInstance();
parent::tearDown();
}
private function scanFixtures(): void
{
$classLoader = require dirname(__DIR__, 3).'/vendor/autoload.php';
$collection = new ComponentCollection();
$scanner = new ComponentScanner(
classLoader: $classLoader,
componentCollection: $collection,
namespacesToScan: ['App\\Tests\\Command\\fixtures']
);
$scanner->scan();
ComponentCollection::setInstance($collection);
}
public function testCommandIsRegisteredByAttributeName(): void
{
$console = new SymfonyConsoleApplication('app');
$console->setCommandLoader(/* FactoryCommandLoader + 收集到的命令工厂 */);
$this->assertTrue($console->has('app:hello'));
}
public function testRunCommandThroughApplication(): void
{
$console = new SymfonyConsoleApplication('app');
$exitCode = $console->run(
new ArrayInput(['app:hello', 'name' => 'kuiper']),
new BufferedOutput()
);
$this->assertSame(0, $exitCode);
}
}装配细节(FactoryCommandLoader 的构建、配置键注入)参见 console/tests/ConsoleApplicationConfigurationTest.php——它覆盖了以下行为,业务项目可对照编写:
| 测试场景 | 断言要点 |
|---|---|
#[AsCommand] 组件注册 | 命令以属性上的 name 注册 |
__invoke() 命令调用 | 不写 execute() 的命令在旧版 Symfony 上也能执行 |
v0.8 #[Command] 兼容 | 命令名来自属性;实例缺名字时自动 setName() |
| 配置注册 | application.commands 条目按配置键注册 |
| 名字校验 | 配置键与命令自身名字不一致抛 InvalidArgumentException |
| 同名覆盖 | 组件命令优先于同名配置条目 |
| 类型校验 | application.commands 非数组、条目非字符串时抛异常 |
| 默认应用名 | application.name 未配置时应用名为 app |
| 默认命令 | application.default_command 生效 |
测试最佳实践
1. 命令逻辑与容器解耦
命令只通过构造函数接收依赖,测试就不需要容器。把业务逻辑进一步下沉到服务类,命令只做输入输出转换,服务类的测试与命令测试各管各的:
php
// 命令薄、服务厚:命令测试只验证参数解析与输出格式
public function __invoke(InputInterface $input, OutputInterface $output): int
{
$result = $this->importService->import($input->getArgument('file'));
$output->writeln(sprintf('imported %d rows', $result));
return Command::SUCCESS;
}2. 不要在测试里依赖全局组件状态
ComponentCollection 是进程级单例,注册装配测试必须在 setUp() 里 clearInstance() 重新扫描、在 tearDown() 里再次清理,避免污染同进程的其他测试。
3. 命令名写错的失败要尽早
application.commands 的键与命令自身名字不一致时,装配期就会抛异常。业务测试里如果用配置方式注册命令,至少加一条冒烟测试验证容器能构建成功——这会把「命令名笔误」拦截在部署前而不是线上首次执行时。
下一步
- 配置指南 - 命令注册相关的配置键
- runtime 模块 - 命令行入口如何启动