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预期。PHPUnit文档中有一些示例。

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

$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);

我希望这足以让你探索各种可能性,并为你的功能提供所需的覆盖范围。

祝你测试愉快!

最新更新