Symfony 4 中的功能测试事件和订阅者

Functional Testing Events and Subscribers in Symfony 4

我需要在 Symfony 4 中对订户进行功能测试,但我在寻找方法时遇到了问题。订阅者具有以下结构

/**
* Class ItemSubscriber
*/
class ItemSubscriber implements EventSubscriberInterface
{
    /**
     * @var CommandBus
     */
    protected $commandBus;

    /**
     * Subscriber constructor.
     *
     * @param CommandBus $commandBus
     */
    public function __construct(CommandBus $commandBus)
    {
        $this->commandBus = $commandBus;
    }

    /**
     * {@inheritdoc}
     */
    public static function getSubscribedEvents()
    {
        return [
            CommandFailedEvent::NAME => 'onCommandFailedEvent',
        ];
    }

    /**
     * @param CommandFailedEvent $event
     *
     * @throws Exception
     */
    public function onCommandFailedEvent(CommandFailedEvent $event)
    {
        $item = $event->getItem();
        $this->processFailed($item);
    }

    /**
     * Sends message 
     *
     * @param array $item
     *
     * @throws Exception
     */
    private function processFailed(array $item)
    {
        $this->commandBus->handle(new UpdateCommand($item));
    }
}

订阅者的流程正在接收内部事件并通过命令总线通过 rabbit 向另一个项目发送消息。

如何测试调度事件 CommandFailedEvent processFailed(array $item) 中的行是否已执行?

有人有关于在 Symfony 4 中测试事件和订阅者的最佳实践的文档吗?

如果您想测试正在调用的命令总线处理程序的过程,您可以测试依赖方法调用,感谢 mock expects. You have some examples in the PHPUnit documentation

例如,你会有这样的东西:

$commandBus = $this->getMockBuilder(CommandBus::class)->disableOriginalConstructor()->getMock();
$commandBus->expects($this->once())->method('handle');

// Create your System Under Test
$SUT = new CommandFailedSubscriber($commandBus);

// Create event
$item = $this->getMockBuilder(YourItem::class)->getMock();
$event = new CommandFailedEvent($item);

// Dispatch your event
$dispatcher = new EventDispatcher();
$dispatcher->addSubscriber($SUT);
$dispatcher->dispatch($event);

我希望这足以让您探索各种可能性并涵盖您的功能所需的内容。

测试愉快!