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

标签 php testing events symfony4 functional-testing

我需要在 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 .您在 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);

我希望这足以让您探索可能性并获得您的功能所需的覆盖范围。

祝你测试愉快!

关于php - Symfony 4 中的功能测试事件和订阅者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60541522/

相关文章:

java - 使用 maven surefire 将失败的测试详细信息输出到标准输出

javascript - 将客户端处理程序从内容页添加到母版页控件

php - 如何搜索部分/屏蔽字符串?

php - 与 PHP 共享 Laravel 身份验证/ session

php - 使用 Imagick 将每个 PDF 页面保存为图像

javascript - Javascript 事件处理程序未按预期触发

c - 如何在使用 XCB 启动新应用程序时获取事件

php - 提供带有数组的准备好的语句

testing - 如何在 playframework 中测试 Jobs?

java - REST ASSURED TEST 创建我自己的 given() 方法