Skip to content

事件测试 ​

测试概述 ​

事件模块的测试围绕两个问题:

  • 业务监听器: 收到事件后行为是否正确——直接实例化事件对象与监听器即可
  • 事件分发: 业务代码是否在正确的时机分发了事件——用 InMemoryEventDispatcher 替换容器里的分发器

框架提供两个开箱即用的测试替身:

类用途
InMemoryEventDispatcher只记录事件、不执行监听器;断言事件是否分发、分发了几次
NullEventDispatcher空实现(实现 PSR-14 接口 + 注册表接口);让需要分发器与注册表的对象安静运行

单元测试 ​

测试监听器逻辑 ​

监听器就是普通类,构造事件对象直接调用 __invoke():

php
<?php

declare(strict_types=1);

namespace App\Tests\Listener;

use App\Event\UserRegistered;
use App\Listener\SendWelcomeMail;
use PHPUnit\Framework\TestCase;

class SendWelcomeMailTest extends TestCase
{
    public function testSendsMailOnUserRegistered(): void
    {
        $mailer = $this->createMock(MailerInterface::class);
        $mailer->expects($this->once())
            ->method('send')
            ->with($this->callback(fn (string $to): bool => str_contains($to, 'u123')));

        $listener = new SendWelcomeMail($mailer);
        $listener->__invoke(new UserRegistered('u123'));
    }
}

测试事件类的事件名声明 ​

getSubscribedEvent() 的返回值就是注册事件名,写错(例如拼错类名常量)会导致监听器永远收不到事件,值得单独断言:

php
<?php

declare(strict_types=1);

use App\Event\UserRegistered;
use App\Listener\SendWelcomeMail;
use PHPUnit\Framework\TestCase;

class SendWelcomeMailEventNameTest extends TestCase
{
    public function testSubscribesToTheRightEvent(): void
    {
        $listener = new SendWelcomeMail();

        $this->assertSame(UserRegistered::class, $listener->getSubscribedEvent());
    }
}

验证事件被分发 ​

用 InMemoryEventDispatcher 替换分发器 ​

InMemoryEventDispatcher 的 dispatch() 只把事件记进数组,不执行任何监听器。把它注入被测对象,事后用 getEvents() 断言:

php
<?php

declare(strict_types=1);

namespace App\Tests\Service;

use App\Event\UserRegistered;
use App\Service\UserService;
use kuiper\event\InMemoryEventDispatcher;
use PHPUnit\Framework\TestCase;

class UserServiceTest extends TestCase
{
    public function testDispatchesUserRegisteredEvent(): void
    {
        $dispatcher = new InMemoryEventDispatcher();
        $service = new UserService($dispatcher /* 其他依赖 */);

        $service->register('u123');

        $events = $dispatcher->getEvents();
        $this->assertCount(1, $events);
        $this->assertInstanceOf(UserRegistered::class, $events[0]);
        $this->assertSame('u123', $events[0]->userId);
    }

    public function testNoEventWhenRegistrationFails(): void
    {
        $dispatcher = new InMemoryEventDispatcher();
        $service = new UserService($dispatcher /* 依赖缺失的注册逻辑 */);

        // 业务失败路径不应分发事件
        $this->expectException(\DomainException::class);
        $service->register('');

        $this->assertSame([], $dispatcher->getEvents());
    }
}

测试结束后可用 clear() 清空记录(每个测试方法新建实例即可,通常不需要)。

NullEventDispatcher 的适用场景 ​

被测代码除了分发事件还注册监听器(例如基于 EventDispatcherAwareTrait 的组件)时,InMemoryEventDispatcher 只实现 PSR-14 接口不够用——NullEventDispatcher 同时实现 EventRegistryInterface(addListener() / reset() 均为空操作),可以直接注入而不抛类型错误。

集成测试 ​

端到端验证监听器注册 ​

验证 #[EventListener] 组件与 application.listeners 配置被正确收集时,参照 kuiper/event 自身的测试方式:扫描组件、构建配置类、调用 createEventDispatcher() 后分发事件。

要点(与 EventConfiguration 的实现一致):

  1. 监听器注册发生在第一次 dispatch(),构建分发器后立刻断言 getDelegateEventDispatcher()->getListeners(...) 是拿不到监听器的
  2. 触发一次 dispatch() 后监听器才会就位
  3. 无法注册的监听器不会抛异常,而是记录 warning 日志——用可检查的日志器(如 Monolog 的 TestHandler,见日志测试)断言跳过原因
php
<?php

declare(strict_types=1);

use kuiper\event\EventDispatcher;
use kuiper\event\LazyEventDispatcher;
use kuiper\event\EventListenerInterface;
use Psr\EventDispatcher\EventDispatcherInterface;

final class OrderPlaced
{
}

final class NotifyWarehouse implements EventListenerInterface
{
    public array $handled = [];

    public function __invoke(object $event): void
    {
        $this->handled[] = $event;
    }

    public function getSubscribedEvent(): string
    {
        return OrderPlaced::class;
    }
}

// 组装与分发
$registry = new EventDispatcher();
$dispatcher = new LazyEventDispatcher($registry, function () use ($registry, $notify): void {
    $registry->addListener(OrderPlaced::class, $notify);
});

$dispatcher->dispatch(new OrderPlaced());

$this->assertCount(1, $notify->handled);

测试传播停止 ​

use 了 StoppableEventTrait 的事件在监听器里调用 stopPropagation() 后,后续监听器不再执行。集成测试可以用两个监听器验证顺序与中断:

php
<?php

declare(strict_types=1);

use kuiper\event\EventDispatcher;
use kuiper\event\StoppableEventTrait;

final class StopAfterFirst
{
    public function __invoke(object $event): void
    {
        $event->stopPropagation();
    }
}

final class ShouldNotRun
{
    public bool $ran = false;

    public function __invoke(object $event): void
    {
        $this->ran = true;
    }
}

final class Broadcast
{
    use StoppableEventTrait;
}

$dispatcher = new EventDispatcher();
$shouldNotRun = new ShouldNotRun();
$dispatcher->addListener(Broadcast::class, new StopAfterFirst());
$dispatcher->addListener(Broadcast::class, $shouldNotRun);

$dispatcher->dispatch(new Broadcast());

$this->assertFalse($shouldNotRun->ran);

测试最佳实践 ​

1. 断言事件名,而不是依赖隐式类名 ​

自定义事件名(dispatchNamed())是字符串,写错不会报类型错误。给分发自定义事件名的代码写测试时,断言 InMemoryEventDispatcher 收到的事件类型,并用独立用例覆盖事件名字符串本身。

2. 集成测试注意监听器只注册一次 ​

LazyEventDispatcher 初始化失败后可重试,但成功后不会再注册。集成测试里如果中途修改了监听器集合(一般不会),记得分发器不会自动感知。

3. 用接口注入便于替换 ​

业务代码注入 Psr\EventDispatcher\EventDispatcherInterface(或需要命名分发时注入 NamedEventDispatcherInterface),测试就能无痛替换成 InMemoryEventDispatcher。

下一步 ​

基于 MIT 许可发布