Skip to content

运行时测试 ​

测试概述 ​

runtime 是应用入口,单测它通常意味着三类断言:

  • 配置装配: 给定配置文件与环境变量,容器构建出来的 bean / 配置是否符合预期
  • Runner 选择: 不同应用类型与 SERVER_MODE 组合下选中的 runner 是否正确
  • 生命周期事件: 请求开始 / 结束事件是否按语义分发

框架自身的测试(runtime/tests/)覆盖了这三维:RuntimeTest / RuntimeOptionsTest / RuntimeRunnerTest / RuntimeContainerTest / AutoConfigurationLoaderTest / MappedRequestHandlerTest / RequestLifecycleTest / RuntimeDotenvTest(后者用临时工程目录 + .env 验证默认加载、disable_dotenv 与 dotenv_path,并断言 composer.json 的硬依赖契约)。业务项目一般只测应用自己的 handler,把 runtime 当作已验证的装配层。

构造 Runtime 实例 ​

Runtime 构造选项全量透传 Symfony Runtime;单测里固定环境的常用组合:

php
<?php

declare(strict_types=1);

use kuiper\runtime\Runtime;
use PHPUnit\Framework\TestCase;

class MyAppRuntimeTest extends TestCase
{
    public function testBuildsRuntime(): void
    {
        $runtime = new Runtime([
            'project_dir' => '/tmp/my-project',
            'env' => 'test',
            'debug' => true,
            'disable_dotenv' => true,   // 测试进程不要加载 .env
            'error_handler' => false,
        ]);

        $container = $runtime->getContainer();
        $this->assertTrue($container->has(AppHandler::class));
    }
}

要点:

  • project_dir 必填(缺失抛 RuntimeException),指向一个含 vendor/autoload.php 与 composer.json 的目录
  • disable_dotenv: true 隔离测试进程与本机 .env;环境变量用 putenv() / $_ENV 注入并在 tearDown() 还原
  • Swoole 场景下 getContainer() 与 worker 内重建的容器是两个实例——依赖容器单例状态的断言要在重建后的容器上做

测试配置装配 ​

验证自动装配清单与配置文件叠加时,参考 AutoConfigurationLoaderTest 的做法:准备一个临时项目目录(composer.json + vendor/composer/installed.json + src/config.php),再调用 Runtime::getContainer() 断言 bean 存在:

php
<?php

declare(strict_types=1);

use kuiper\runtime\Runtime;
use PHPUnit\Framework\TestCase;

class AutoWiringTest extends TestCase
{
    public function testAutoConfigurationRegistersFrameworkBeans(): void
    {
        $runtime = new Runtime([
            'project_dir' => $this->makeTempProject(),
            'disable_dotenv' => true,
            'error_handler' => false,
        ]);

        $container = $runtime->getContainer();
        // 框架配置类自动注册后,bean 无需手工声明
        $this->assertTrue($container->has(Psr\EventDispatcher\EventDispatcherInterface::class));
    }
}

自动装配聚合结果是纯 JSON 缓存(cache/kuiper-auto-configuration.json),测试项目目录必须是临时的,避免读到业务项目的缓存。

测试生命周期事件 ​

RequestLifecycleTrait 的分发逻辑可用带记录的事件分发器直接验证;HTTP 层则构造 runner:

php
<?php

declare(strict_types=1);

use kuiper\runtime\MappedRequestHandler;
use kuiper\runtime\event\RequestFinished;
use kuiper\runtime\event\RequestStarted;
use PHPUnit\Framework\TestCase;
use Psr\EventDispatcher\EventDispatcherInterface;

class RequestLifecycleTest extends TestCase
{
    public function testHandlerExceptionsStillDispatchRequestFinished(): void
    {
        $events = [];
        $dispatcher = new class($events) implements EventDispatcherInterface {
            public function __construct(private array &$events) {}

            public function dispatch(object $event): object
            {
                $this->events[] = $event;

                return $event;
            }
        };

        $failingHandler = new class implements \Psr\Http\Server\RequestHandlerInterface {
            public function handle(\Psr\Http\Message\ServerRequestInterface $request): \Psr\Http\Message\ResponseInterface
            {
                throw new \RuntimeException('boom');
            }
        };

        // Psr15Runner 异常路径同样分发 RequestFinished(response 为 null)后 re-throw
        $creator = /* 由 PSR-17 工厂组装的 ServerRequestCreator */;
        $runner = new \kuiper\runtime\Psr15Runner($failingHandler, $creator, $dispatcher);

        try {
            $runner->run();
            $this->fail('expected exception to be re-thrown');
        } catch (\RuntimeException) {
            $this->assertCount(2, $events);
            $this->assertInstanceOf(RequestStarted::class, $events[0]);
            $this->assertInstanceOf(RequestFinished::class, $events[1]);
            $this->assertNotNull($events[1]->getException());
            $this->assertNull($events[1]->getResponse());
        }
    }
}

测试 MappedRequestHandler ​

纯内存对象,无需任何 SAPI:

php
<?php

declare(strict_types=1);

use kuiper\runtime\MappedRequestHandler;
use PHPUnit\Framework\TestCase;

class RouteMappingTest extends TestCase
{
    public function testPathPrefixMatching(): void
    {
        $request = $this->createRequest('/rpc/user/get');
        $isMatch = MappedRequestHandler::byPathPrefix('rpc');

        $this->assertTrue($isMatch($request));
        // /rpcs 不匹配 /rpc 前缀
        $this->assertFalse($isMatch($this->createRequest('/rpcs/x')));
    }

    private function createRequest(string $path): \Psr\Http\Message\ServerRequestInterface
    {
        return (new \Nyholm\Psr7\ServerRequest('GET', 'http://localhost'.$path));
    }
}

测试最佳实践 ​

1. 不要在单测里启动真实服务器 ​

runner 选择、Swoole/FrankenPHP 行为由框架测试覆盖;业务测试聚焦 handler 与配置。需要端到端验证时,用 php -S 起开发服务器做冒烟,而不是在 PHPUnit 里起服务。

2. 环境变量注入即用即清 ​

SERVER_MODE、COMPONENT_SCAN_CACHE_*、AUTO_CONFIGURATION_ENABLED 都是进程级读取,setUp() 写入、tearDown() 还原,避免污染同进程的其他测试。

3. 配置文件用独立副本 ​

测试项目的 src/config.php 放在临时目录,不要指向业务项目真实配置——application.config_file 指到哪就读哪。

下一步 ​

基于 MIT 许可发布